diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f2deecb9c4..bf42cb8394 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -309,7 +309,6 @@ variables: refs: - merge_requests changes: - - "src/karathon/**/*" # bound api old binding code - "src/karabind/**/*" # bound api new binding code - "src/karabo/**/*" # bound api depends on the c++ build - "src/pythonKarabo/**/*" diff --git a/auto_build_all.sh b/auto_build_all.sh index efcc213534..375b3f0315 100755 --- a/auto_build_all.sh +++ b/auto_build_all.sh @@ -488,7 +488,7 @@ if [ -d $FRAMEWORK_INSTALL_DIR ]; then done fi -# Builds libkarabo, libkarathon, libkarabind, karabo-* utilities +# Builds libkarabo, libkarabind, karabo-* utilities # and installs them in FRAMEWORK_INSTALL_DIR. safeRunCommand $EXTERN_DEPS_DIR/bin/cmake --build . -j $NUM_JOBS --target install if [ $? -ne 0 ]; then diff --git a/build/karabo/bundle.sh b/build/karabo/bundle.sh index 0519991ffb..3aa1e49c5b 100755 --- a/build/karabo/bundle.sh +++ b/build/karabo/bundle.sh @@ -101,14 +101,12 @@ mkdir -p $PACKAGEDIR/var/data cp -rf $EXTERN_DEPS_DIR $PACKAGEDIR/extern rm -rf $PACKAGEDIR/extern/conan_toolchain -# karathon and karabind +# karabind # Use karabo embedded python interpreter PATH=$PACKAGEDIR/extern/bin:$PATH SITE_PACKAGES=`python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"` -cp -rf $PACKAGEDIR/lib/libkarathon.so $SITE_PACKAGES/karathon.so # <-- karathon.so cp -rf $PACKAGEDIR/lib/libkarabind.so $SITE_PACKAGES/karabind.so # <-- karabind.so -# ln -s $SITE_PACKAGES/karathon.so $PACKAGEDIR/lib/libkarathon.so [ -d $PACKAGEDIR/extern/include/python3.8m ] && (cd $PACKAGEDIR/extern/include; rm -f python3.8; ln -s python3.8m python3.8) # deviceServer, brokerMessageLogger, idxview, idxbuild, brokerRates are diff --git a/ci/lint b/ci/lint index f2ef9c7efd..05289d63cb 100755 --- a/ci/lint +++ b/ci/lint @@ -52,7 +52,7 @@ __lint_clang_format() { SCAN_DIRS="$CI_PROJECT_DIR/src/karabo $CI_PROJECT_DIR/src/brokerMessageLogger \ $CI_PROJECT_DIR/src/cppLongTests $CI_PROJECT_DIR/src/deviceServer \ - $CI_PROJECT_DIR/src/integrationTests $CI_PROJECT_DIR/src/karathon \ + $CI_PROJECT_DIR/src/integrationTests \ $CI_PROJECT_DIR/src/karabind $CI_PROJECT_DIR/src/tools" echo "Linting format with `clang-format --version` ..." diff --git a/run_python_tests.sh b/run_python_tests.sh index 34259abff9..955282b784 100755 --- a/run_python_tests.sh +++ b/run_python_tests.sh @@ -131,18 +131,12 @@ safeRunTests() { fi export KARABO_BROKER=$BROKER - if [ "$USE_KARATHON" = "1" ]; then - BIND_MODE="Running tests with karathon" - else - BIND_MODE="Running tests with karabind" - fi echo echo "*************************************************************************************************" echo "*************************************************************************************************" echo "**" echo "** Running Karabo Python ${TEST_SUITE_NAME} tests with ${BROKER_TYPE^^} broker ... ${KARABO_BROKER}" echo "** Broker Topic is ${KARABO_BROKER_TOPIC}" - echo "** Python bindings: ${BIND_MODE}" echo "**" echo "*************************************************************************************************" echo "*************************************************************************************************" @@ -175,10 +169,6 @@ runPythonTestsCI() { do safeRunTests $BROKER $* done - # On CI we run once with karathon - export USE_KARATHON="1" - safeRunTests $BROKER $* - unset USE_KARATHON } runPythonTests() { diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5cb5e71bdb..2366cfa137 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ # WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. # The project that builds the various C++ components of the Karabo Framework: -# libkarabo, libkarathon, C++ device server, unit tests, integration tests, +# libkarabo, C++ device server, unit tests, integration tests, # and karabo C++ utilities like BrokerMessageLogs, BrokerMessageRates, ... # # Variables that influence the configuration behavior and that should be @@ -116,9 +116,6 @@ endif() # is used. add_subdirectory(karabo ${CMAKE_BINARY_DIR}/karabo) -# The build of the Karathon Library (used by the Bound Python API). -add_subdirectory(karathon ${CMAKE_BINARY_DIR}/karathon) - # The build of the Karabind Library (used by the Bound Python API). add_subdirectory(karabind ${CMAKE_BINARY_DIR}/karabind) @@ -171,7 +168,6 @@ if (BUILD_UNIT_TESTING OR BUILD_INTEGRATION_TESTING OR BUILD_LONG_RUN_TESTING) "*/include/numpy/*" "${CMAKE_CURRENT_SOURCE_DIR}/tools/*" "${CMAKE_CURRENT_SOURCE_DIR}/deviceServer/*" "${CMAKE_CURRENT_SOURCE_DIR}/brokerMessageLogger/*" - "${CMAKE_CURRENT_SOURCE_DIR}/karathon/*" "${CMAKE_CURRENT_SOURCE_DIR}/karabind/*" "${CMAKE_CURRENT_SOURCE_DIR}/integrationTests/*" "${CMAKE_CURRENT_SOURCE_DIR}/cppLongTests/*" diff --git a/src/karathon/AttributesNodeWrap.hh b/src/karathon/AttributesNodeWrap.hh deleted file mode 100644 index 7ba2914bfc..0000000000 --- a/src/karathon/AttributesNodeWrap.hh +++ /dev/null @@ -1,156 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: AttributesNodeWrap.hh - * Author: esenov - * - * Created on March 20, 2013, 2:28 PM - */ - -#ifndef ATTRIBUTESNODEWRAP_HH -#define ATTRIBUTESNODEWRAP_HH - -#include -#include -#include - -#include "Wrapper.hh" - -namespace bp = boost::python; - -namespace karathon { - - class AttributesNodeWrap { - struct null_deleter { - void operator()(void const*) const {} - }; - - public: - typedef boost::shared_ptr Pointer; - - static bp::object getKey(const Pointer& node) { - return bp::object(node->getKey()); - } - - static void setValue(const Pointer& node, const bp::object& obj) { - boost::any any; - Wrapper::toAny(obj, any); - node->setValue(any); - } - - static bp::object getValue(const Pointer& node) { - using namespace karabo::util; - boost::any& a = node->getValueAsAny(); - // handle Hash differently returning reference to Hash - if (a.type() == typeid(Hash)) { - Hash& hash = boost::any_cast(a); - boost::shared_ptr p(&hash, null_deleter()); - return bp::object(p); - } - return Wrapper::toObject(a); - } - - static bp::object getValueAs(const Pointer& node, const bp::object& o_type) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - reftype = Types::from(type); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - reftype = PyTypes::to(type); - } - - switch (reftype) { - case Types::BOOL: - return bp::object(node->getValueAs()); - case Types::CHAR: - return bp::object(node->getValueAs()); - case Types::INT8: - return bp::object(node->getValueAs()); - case Types::UINT8: - return bp::object(node->getValueAs()); - case Types::INT16: - return bp::object(node->getValueAs()); - case Types::UINT16: - return bp::object(node->getValueAs()); - case Types::INT32: - return bp::object(node->getValueAs()); - case Types::UINT32: - return bp::object(node->getValueAs()); - case Types::INT64: - return bp::object(node->getValueAs()); - case Types::UINT64: - return bp::object(node->getValueAs()); - case Types::FLOAT: - return bp::object(node->getValueAs()); - case Types::DOUBLE: - return bp::object(node->getValueAs()); - case Types::STRING: - return bp::object(node->getValueAs()); - case Types::VECTOR_BOOL: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_CHAR: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_INT8: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_UINT8: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_INT16: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT16: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_INT32: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT32: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_INT64: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT64: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - // case Types::HASH: - // return bp::object(node->getValueAs()); - // case Types::VECTOR_HASH: - // return Wrapper::fromStdVectorToPyList(node->getValueAs()); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - static bp::object getType(const Pointer& node) { - using namespace karabo::util; - PyTypes::ReferenceType type = static_cast(node->getType()); - return bp::object(type); - } - - static void setType(const Pointer& node, const bp::object& o_type) { - using namespace karabo::util; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - node->setType(Types::from(type)); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - node->setType(PyTypes::to(type)); - } - } - }; -} // namespace karathon - -#endif /* ATTRIBUTESNODEWRAP_HH */ diff --git a/src/karathon/AttributesWrap.hh b/src/karathon/AttributesWrap.hh deleted file mode 100644 index e54f0796c3..0000000000 --- a/src/karathon/AttributesWrap.hh +++ /dev/null @@ -1,201 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: AttributesWrap.hh - * Author: esenov - * - * Created on March 20, 2013, 10:15 AM - */ - -#ifndef ATTRIBUTESWRAP_HH -#define ATTRIBUTESWRAP_HH - -#include -#include -#include -#include - - -namespace karathon { - - class AttributesWrap { - struct null_deleter { - void operator()(void const*) const {} - }; - - public: - static bool has(karabo::util::Hash::Attributes& self, const std::string& key) { - return self.has(key); - } - - static bool is(karabo::util::Hash::Attributes& self, const std::string& key, const std::string& type) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::from(type); - return self.is(key, reftype); - } - - static void erase(karabo::util::Hash::Attributes& self, const std::string& key) { - self.erase(key); - } - - static bp::object size(karabo::util::Hash::Attributes& self) { - return bp::object(self.size()); - } - - static bool empty(karabo::util::Hash::Attributes& self) { - return self.empty(); - } - - static void clear(karabo::util::Hash::Attributes& self) { - self.clear(); - } - - static bp::object getNode(karabo::util::Hash::Attributes& self, const std::string& key) { - using namespace karabo::util; - Hash::Attributes::Node& nodeRef = self.getNode(key); - boost::optional node(nodeRef); - return bp::object(boost::shared_ptr(&(*node), null_deleter())); - } - - static bp::object get(karabo::util::Hash::Attributes& self, const std::string& key) { - return Wrapper::toObject(self.getAny(key)); - } - - static bp::object getAs(karabo::util::Hash::Attributes& self, const std::string& key, - const bp::object& o_type) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - reftype = Types::from(type); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - reftype = PyTypes::to(type); - } - - switch (reftype) { - case Types::BOOL: - return bp::object(self.getAs(key)); - case Types::CHAR: - return bp::object(self.getAs(key)); - case Types::INT8: - return bp::object(self.getAs(key)); - case Types::UINT8: - return bp::object(self.getAs(key)); - case Types::INT16: - return bp::object(self.getAs(key)); - case Types::UINT16: - return bp::object(self.getAs(key)); - case Types::INT32: - return bp::object(self.getAs(key)); - case Types::UINT32: - return bp::object(self.getAs(key)); - case Types::INT64: - return bp::object(self.getAs(key)); - case Types::UINT64: - return bp::object(self.getAs(key)); - case Types::FLOAT: - return bp::object(self.getAs(key)); - case Types::DOUBLE: - return bp::object(self.getAs(key)); - case Types::STRING: - return bp::object(self.getAs(key)); - case Types::VECTOR_BOOL: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_CHAR: - return Wrapper::fromStdVectorToPyByteArray(self.getAs(key)); - case Types::VECTOR_INT8: - return Wrapper::fromStdVectorToPyByteArray(self.getAs(key)); - case Types::VECTOR_UINT8: - return Wrapper::fromStdVectorToPyByteArray(self.getAs(key)); - case Types::VECTOR_INT16: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_UINT16: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_INT32: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_UINT32: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_INT64: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - case Types::VECTOR_UINT64: - return Wrapper::fromStdVectorToPyArray(self.getAs(key)); - // case Types::HASH: - // return bp::object(self.getAs(key)); - // case Types::VECTOR_HASH: - // return Wrapper::fromStdVectorToPyList(self.getAs(key)); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - static bp::object set(karabo::util::Hash::Attributes& self, const std::string& key, const bp::object& value) { - boost::any any; - Wrapper::toAny(value, any); - return bp::object(self.set(key, any)); - } - - // static bp::object find(karabo::util::Hash::Attributes& self, const std::string& key) { - // karabo::util::Hash::Attributes::const_map_iterator it = self.find(key); - // if (it == self.mend()) - // return bp::object(); - // return bp::object(it); - // } - // - // static bp::object getIt(karabo::util::Hash::Attributes& self, const bp::object& obj) { - // if (bp::extract(obj).check()) { - // karabo::util::Hash::Attributes::const_map_iterator it = - // bp::extract(obj); boost::any any = - // self.get(it); std::cout << "getIt for const_map_iterator:" << any.type().name() << - // std::endl; return Wrapper::toObject(any); - // } else if (bp::extract(obj).check()) { - // std::cout << "getIt for map_iterator:" << std::endl; - // karabo::util::Hash::Attributes::map_iterator it = - // bp::extract(obj); return - // Wrapper::toObject(self.get(it)); - // } - // throw KARABO_NOT_SUPPORTED_EXCEPTION("Python type cannot be converted to - // Hash::Attributes::map_iterator"); - // } - - static bp::object __getitem__(karabo::util::Hash::Attributes& self, const bp::object& obj) { - if (bp::extract(obj).check()) { - karabo::util::Hash::Attributes::Node& node = bp::extract(obj); - if (node.getType() == karabo::util::Types::HASH) { - boost::shared_ptr hash = - boost::shared_ptr(&node.getValue(), null_deleter()); - return bp::object(hash); - } - return Wrapper::toObject(node.getValueAsAny(), false); - } else if (bp::extract(obj).check()) { - karabo::util::Hash::Attributes::Node& node = self.getNode(bp::extract(obj)); - if (node.getType() == karabo::util::Types::HASH) { - boost::shared_ptr hash = - boost::shared_ptr(&node.getValue(), null_deleter()); - return bp::object(hash); - } - return Wrapper::toObject(node.getValueAsAny(), false); - } - throw KARABO_PYTHON_EXCEPTION("Invalid type for Hash index. The type should be 'Node' or 'str'!"); - } - }; -} // namespace karathon - -#endif /* ATTRIBUTESWRAP_HH */ diff --git a/src/karathon/CMakeLists.txt b/src/karathon/CMakeLists.txt deleted file mode 100644 index 1b22f753ba..0000000000 --- a/src/karathon/CMakeLists.txt +++ /dev/null @@ -1,105 +0,0 @@ -# This file is part of Karabo. -# -# http://www.karabo.eu -# -# Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. -# -# Karabo is free software: you can redistribute it and/or modify it under -# the terms of the MPL-2 Mozilla Public License. -# -# You should have received a copy of the MPL-2 Public License along with -# Karabo. If not, see . -# -# Karabo is distributed in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. - -cmake_minimum_required(VERSION 3.15) - -project( - "KarathonLib" - LANGUAGES C CXX -) - -include("../cmake/cxx-options.cmake") -include("../cmake/karabo-lib-target-name.cmake") - -set(KARATHON_LIB_TARGET_NAME "karathon") - -# Uses Python3_ROOT_DIR to avoid other Python interpreters that maybe on the -# system with wrong NumPy version or no NumPy package at all. -set(Python3_ROOT_DIR ${CMAKE_PREFIX_PATH}) -find_package( - Python3 3.11 EXACT REQUIRED - COMPONENTS Interpreter Development NumPy -) - -message(STATUS "Found NumPy version '${Python3_NumPy_VERSION}'.") -message(STATUS "NumPy include dirs = '${Python3_NumPy_INCLUDE_DIRS}'") - -# From Boost 1.67 onwards, the identifier of the Boost Python component -# requires a suffix with the version of Python the Boost Python package has -# been built against. More details at: -# https://stackoverflow.com/questions/56067518/cmake-could-not-find-boost-python - -find_package(Boost REQUIRED COMPONENTS python311) - -file(GLOB_RECURSE KARATHON_SRCS CONFIGURE_DEPENDS "*.cc") - -add_library( - ${KARATHON_LIB_TARGET_NAME} SHARED - ${KARATHON_SRCS} -) - -# The last two RPATH entries are for when libkarathon.so is packaged as -# karathon.so inside INSTALL_PACKAGE_ROOT/extern/lib/python3.11/site-packages. -set_target_properties( - ${KARATHON_LIB_TARGET_NAME} PROPERTIES - INSTALL_RPATH "$ORIGIN/../extern/lib;$ORIGIN;$ORIGIN/../../../../lib;$ORIGIN/../.." -) - -# To avoid warnings about deprecated version for NumPy API. -target_compile_definitions( - ${KARATHON_LIB_TARGET_NAME} - PRIVATE - NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION -) - -# Options lifted from the legacy Netbeans based project. -target_compile_options( - ${KARATHON_LIB_TARGET_NAME} - PRIVATE - -Wfatal-errors - -Wno-unused-local-typedefs - -Wno-noexcept-type - -Wall) - -target_include_directories( - ${KARATHON_LIB_TARGET_NAME} - PUBLIC - ${Python3_INCLUDE_DIRS} - ${Python3_NumPy_INCLUDE_DIRS} - # The Boost Python include directories are "inherited" from the - # Karabo lib dependency - they are on the same tree as the other - # components of Boost that libkarabo already used. -) - -target_link_libraries( - ${KARATHON_LIB_TARGET_NAME} - ${KARABO_LIB_TARGET_NAME} - boost::python311 - ${PYTHON_LIBRARIES} -) - -install( - TARGETS ${KARATHON_LIB_TARGET_NAME} - LIBRARY DESTINATION "lib" - PUBLIC_HEADER DESTINATION "include/karathon" - RUNTIME DESTINATION "bin" -) - -# Add karathon header files to the installation tree. -file(GLOB INCLUDE_FILES CONFIGURE_DEPENDS "*.hh") -foreach (FILE_PATH ${INCLUDE_FILES}) - install(FILES ${FILE_PATH} DESTINATION "include/karathon") -endforeach() diff --git a/src/karathon/ChannelWrap.cc b/src/karathon/ChannelWrap.cc deleted file mode 100644 index 092c110148..0000000000 --- a/src/karathon/ChannelWrap.cc +++ /dev/null @@ -1,295 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ChannelWrap.cc - * Author: Sergey Esenov - * - * Created on April 6, 2013, 12:47 AM - */ - -#include "ChannelWrap.hh" - -#include "ScopedGILAcquire.hh" -#include "Wrapper.hh" - -namespace bp = boost::python; -using namespace std; -using namespace karabo::util; -using namespace karabo::net; -using namespace boost::placeholders; - -namespace karathon { - - - bp::object ChannelWrap::readStr(karabo::net::Channel::Pointer channel) { - char* data = 0; - size_t size = 0; - { - ScopedGILRelease nogil; - size = channel->readSizeInBytes(); - data = new char[size]; - channel->read(data, size); - } - PyObject* pyobj = PyUnicode_FromStringAndSize(data, size); - return bp::object(bp::handle<>(pyobj)); - } - - - bp::object ChannelWrap::readHash(karabo::net::Channel::Pointer channel) { - boost::shared_ptr hash(new Hash()); - { - ScopedGILRelease nogil; - channel->read(*hash); - } - return bp::object(hash); - } - - - bp::tuple ChannelWrap::readHashStr(karabo::net::Channel::Pointer channel) { - boost::shared_ptr header(new Hash()); - char* data = 0; - size_t size = 0; - { - ScopedGILRelease nogil; - channel->read(*header); - size = channel->readSizeInBytes(); - data = new char[size]; - channel->read(data, size); - } - PyObject* pyobj = PyUnicode_FromStringAndSize(data, size); - return bp::make_tuple(bp::object(header), bp::object(bp::handle<>(pyobj))); - } - - - bp::tuple ChannelWrap::readHashHash(karabo::net::Channel::Pointer channel) { - boost::shared_ptr header(new Hash()); - boost::shared_ptr body(new Hash()); - { - ScopedGILRelease nogil; - channel->read(*header); - channel->read(*body); - } - return bp::make_tuple(bp::object(header), bp::object(body)); - } - - - void ChannelWrap::write(karabo::net::Channel::Pointer channel, const bp::object& obj) { - if (PyBytes_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyBytes_Size(bytearray); - char* data = PyBytes_AsString(bytearray); - ScopedGILRelease nogil; - channel->write(data, size); - return; - } else if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - ScopedGILRelease nogil; - channel->write(data, size); - return; - } else if (bp::extract(obj).check()) { - const Hash& hash = bp::extract(obj); - ScopedGILRelease nogil; - channel->write(hash); - return; - } else if (PyUnicode_Check(obj.ptr())) { - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(obj.ptr(), &size); - ScopedGILRelease nogil; - channel->write(data, size); - return; - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } - - - void ChannelWrap::write2(karabo::net::Channel::Pointer channel, const bp::object& header, const bp::object& obj) { - if (bp::extract(header).check()) { - const karabo::util::Hash hdr = bp::extract(header); - if (PyBytes_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyBytes_Size(bytearray); - char* data = PyBytes_AsString(bytearray); - ScopedGILRelease nogil; - channel->write(hdr, data, size); - return; - } else if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - ScopedGILRelease nogil; - channel->write(hdr, data, size); - return; - } else if (PyUnicode_Check(obj.ptr())) { - std::string data = bp::extract(obj); - ScopedGILRelease nogil; - channel->write(hdr, data); - return; - } else if (bp::extract(obj).check()) { - const karabo::util::Hash& hash = bp::extract(obj); - ScopedGILRelease nogil; - channel->write(hdr, hash); - return; - } - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } - - - void ChannelWrap::readAsyncStr(karabo::net::Channel::Pointer channel, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "readAsyncStr", channel); - ScopedGILRelease nogil; - channel->readAsyncString(proxyWrap); - } - - - void ChannelWrap::readAsyncHash(karabo::net::Channel::Pointer channel, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "readAsyncHash", channel); - ScopedGILRelease nogil; - channel->readAsyncHash(proxyWrap); - } - - - void ChannelWrap::readAsyncHashStr(karabo::net::Channel::Pointer channel, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "readAsyncHashStr", channel); - ScopedGILRelease nogil; - channel->readAsyncHashString(proxyWrap); - } - - - void ChannelWrap::readAsyncHashHash(karabo::net::Channel::Pointer channel, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "readAsyncHashHash", channel); - ScopedGILRelease nogil; - channel->readAsyncHashHash(proxyWrap); - } - - - void ChannelWrap::writeAsyncStr(karabo::net::Channel::Pointer channel, const bp::object& obj, - const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "writeAsyncStr", channel); - if (PyBytes_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyBytes_Size(bytearray); - char* data = PyBytes_AsString(bytearray); - ScopedGILRelease nogil; - channel->writeAsyncRaw(data, size, proxyWrap); - return; - } - if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - ScopedGILRelease nogil; - channel->writeAsyncRaw(data, size, proxyWrap); - return; - } - if (PyUnicode_Check(obj.ptr())) { - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(obj.ptr(), &size); - ScopedGILRelease nogil; - channel->writeAsyncRaw(data, size, proxyWrap); - return; - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } - - - void ChannelWrap::writeAsyncHash(karabo::net::Channel::Pointer channel, const bp::object& data, - const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - if (bp::extract(data).check()) { - const Hash& h = bp::extract(data); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "writeAsyncHash", channel); - ScopedGILRelease nogil; - channel->writeAsyncHash(h, proxyWrap); - return; - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } - - - void ChannelWrap::writeAsyncHashStr(karabo::net::Channel::Pointer channel, const bp::object& hdr, - const bp::object& body, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - if (bp::extract(hdr).check()) { - const Hash& h = bp::extract(hdr); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "writeAsyncHashStr", channel); - PyObject* bytearray = body.ptr(); - if (PyUnicode_Check(bytearray)) { - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(bytearray, &size); - ScopedGILRelease nogil; - channel->writeAsyncHashRaw(h, data, size, proxyWrap); - return; - } - if (PyBytes_Check(bytearray)) { - size_t size = PyBytes_Size(bytearray); - const char* data = PyBytes_AsString(bytearray); - ScopedGILRelease nogil; - channel->writeAsyncHashRaw(h, data, size, proxyWrap); - return; - } - if (PyByteArray_Check(bytearray)) { - size_t size = PyByteArray_Size(bytearray); - const char* data = PyByteArray_AsString(bytearray); - ScopedGILRelease nogil; - channel->writeAsyncHashRaw(h, data, size, proxyWrap); - return; - } - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } - - - void ChannelWrap::writeAsyncHashHash(karabo::net::Channel::Pointer channel, const bp::object& hdr, - const bp::object& body, const bp::object& handler) { - if (!PyCallable_Check(handler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - if (bp::extract(hdr).check() && bp::extract(body).check()) { - const Hash& header = bp::extract(hdr); - const Hash& data = bp::extract(body); - using Wrap = HandlerWrapExtra; - Wrap proxyWrap(handler, "writeAsyncHashHash", channel); - ScopedGILRelease nogil; - channel->writeAsyncHashHash(header, data, proxyWrap); - return; - } - throw KARABO_PYTHON_EXCEPTION("Not supported type"); - } -} // namespace karathon diff --git a/src/karathon/ChannelWrap.hh b/src/karathon/ChannelWrap.hh deleted file mode 100644 index 1dbc3b2cc5..0000000000 --- a/src/karathon/ChannelWrap.hh +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ChannelWrap.hh - * Author: Sergey Esenov - * - * Created on April 4, 2013, 3:22 PM - */ - -#ifndef KARABO_PYEXFEL_CHANNELWRAP_HH -#define KARABO_PYEXFEL_CHANNELWRAP_HH - -#include -#include - -#include "ScopedGILRelease.hh" - -namespace bp = boost::python; - -namespace karathon { - - class ChannelWrap { - public: - static bp::object getConnection(karabo::net::Channel::Pointer channel) { - karabo::net::Connection::Pointer connection; - { - ScopedGILRelease nogil; - connection = channel->getConnection(); - } - return bp::object(connection); - } - - static bp::object readStr(karabo::net::Channel::Pointer channel); - static bp::object readHash(karabo::net::Channel::Pointer channel); - static bp::tuple readHashStr(karabo::net::Channel::Pointer channel); - static bp::tuple readHashHash(karabo::net::Channel::Pointer channel); - static void write(karabo::net::Channel::Pointer channel, const bp::object& obj); - static void write2(karabo::net::Channel::Pointer channel, const bp::object& header, const bp::object& obj); - static void readAsyncStr(karabo::net::Channel::Pointer channel, const bp::object& handler); - static void readAsyncHash(karabo::net::Channel::Pointer channel, const bp::object& handler); - static void readAsyncHashStr(karabo::net::Channel::Pointer channel, const bp::object& handler); - static void readAsyncHashHash(karabo::net::Channel::Pointer channel, const bp::object& handler); - static void writeAsyncStr(karabo::net::Channel::Pointer channel, const bp::object& data, - const bp::object& handler); - static void writeAsyncHash(karabo::net::Channel::Pointer channel, const bp::object& data, - const bp::object& handler); - static void writeAsyncHashStr(karabo::net::Channel::Pointer channel, const bp::object& hdr, - const bp::object& data, const bp::object& handler); - static void writeAsyncHashHash(karabo::net::Channel::Pointer channel, const bp::object& hdr, - const bp::object& data, const bp::object& handler); - // static void setErrorHandler(karabo::net::Channel::Pointer channel, const bp::object& handler); - - static size_t id(karabo::net::Channel::Pointer channel) { - return size_t(&(*channel)); - } - - static void clear() {} - - private: - static bool hasattr(bp::object obj, const std::string& attrName) { - return PyObject_HasAttrString(obj.ptr(), const_cast(attrName.c_str())); - } - }; - -} // namespace karathon -#endif /* KARABO_PYEXFEL_CHANNELWRAP_HH */ diff --git a/src/karathon/ConnectionWrap.cc b/src/karathon/ConnectionWrap.cc deleted file mode 100644 index bac4092e12..0000000000 --- a/src/karathon/ConnectionWrap.cc +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include "ConnectionWrap.hh" - -#include "Wrapper.hh" - -using namespace std; -using namespace karabo::net; -using namespace karabo::util; -using namespace boost::placeholders; - -namespace bp = boost::python; - - -namespace karathon { - - - int ConnectionWrap::startAsync(const karabo::net::Connection::Pointer& connection, - const bp::object& connectionHandler) { - if (!PyCallable_Check(connectionHandler.ptr())) - throw KARABO_PYTHON_EXCEPTION("Registered object is not a function object."); - int port = 0; - auto proxyWrap = HandlerWrap(connectionHandler, "startAsync"); - try { - ScopedGILRelease nogil; - port = connection->startAsync(proxyWrap); - } catch (...) { - KARABO_RETHROW - } - return port; - } - -} // namespace karathon diff --git a/src/karathon/ConnectionWrap.hh b/src/karathon/ConnectionWrap.hh deleted file mode 100644 index 6c2cdbacb1..0000000000 --- a/src/karathon/ConnectionWrap.hh +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ConnectionWrap.hh - * Author: Sergey Esenov - * - * Created on April 5, 2013, 10:10 AM - */ - -#ifndef KARATHON_CONNECTIONWRAP_HH -#define KARATHON_CONNECTIONWRAP_HH - -#include -#include - -#include "ScopedGILAcquire.hh" -#include "ScopedGILRelease.hh" -#include "karabo/net/Channel.hh" -#include "karabo/net/Connection.hh" -#include "karabo/util/Hash.hh" - - -namespace bp = boost::python; - -namespace karathon { - - class ConnectionWrap { - public: - static bp::object start(const karabo::net::Connection::Pointer& connection) { - karabo::net::Channel::Pointer channel; - { - ScopedGILRelease nogil; - channel = connection->start(); - } - return bp::object(channel); - } - - static void stop(const karabo::net::Connection::Pointer& connection) { - ScopedGILRelease nogil; - connection->stop(); - } - - static int startAsync(const karabo::net::Connection::Pointer& connection, const bp::object& connectionHandler); - }; -} // namespace karathon - -#endif /* KARATHON_CONNECTIONWRAP_HH */ diff --git a/src/karathon/DeviceClientWrap.hh b/src/karathon/DeviceClientWrap.hh deleted file mode 100644 index c34dd1fbdc..0000000000 --- a/src/karathon/DeviceClientWrap.hh +++ /dev/null @@ -1,556 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ComWrap.hh - * Author: - * - * Created on July 11, 2012, 11:22 AM - */ - -#ifndef KARATHON_DEVCOM_HH -#define KARATHON_DEVCOM_HH - -#include -#include -#include -#include - -#include "HashWrap.hh" -#include "PyCoreLockWrap.hh" -#include "ScopedGILAcquire.hh" -#include "ScopedGILRelease.hh" -#include "SignalSlotableWrap.hh" -#include "Wrapper.hh" - -namespace bp = boost::python; -using namespace karabo::xms; - -namespace karathon { - - class DeviceClientWrap : public karabo::core::DeviceClient { - public: - DeviceClientWrap(const std::string& instanceId = std::string()) : DeviceClient(instanceId), m_isVerbose(true) { - boost::shared_ptr p = m_signalSlotable.lock(); - if (!p) { - throw KARABO_PARAMETER_EXCEPTION("Broker connection is not valid."); - } - p->updateInstanceInfo(karabo::util::Hash("lang", "bound")); - m_signalSlotableWrap = boost::static_pointer_cast(p); - } - - DeviceClientWrap(boost::shared_ptr& o) - : DeviceClient(boost::static_pointer_cast(o)), m_isVerbose(true) { - boost::shared_ptr p = m_signalSlotable.lock(); - if (!p) { - throw KARABO_PARAMETER_EXCEPTION("Broker connection is not valid."); - } - m_signalSlotableWrap = boost::static_pointer_cast(p); - } - - ~DeviceClientWrap() {} - - std::string getInstanceIdPy() { - return this->getInstanceId(); - } - - bp::tuple instantiatePy(const std::string& serverId, const karabo::util::Hash& configuration, - int timeoutInSeconds) { - std::pair instantiateReply; - { - ScopedGILRelease nogil; - instantiateReply = this->instantiate(serverId, configuration, timeoutInSeconds); - } - return Wrapper::fromStdPairToPyTuple(instantiateReply); - } - - bp::tuple instantiatePy(const std::string& serverId, const std::string& classId, - const karabo::util::Hash& configuration, int timeoutInSeconds) { - std::pair instantiateReply; - { - ScopedGILRelease nogil; - instantiateReply = this->instantiate(serverId, classId, configuration, timeoutInSeconds); - } - return Wrapper::fromStdPairToPyTuple(instantiateReply); - } - - bp::tuple killDevicePy(const std::string& deviceId, int timeoutInSeconds = -1) { - std::pair killReply; - { - ScopedGILRelease nogil; - killReply = this->killDevice(deviceId, timeoutInSeconds); - } - return Wrapper::fromStdPairToPyTuple(killReply); - } - - bp::tuple killServerPy(const std::string& serverId, int timeoutInSeconds = -1) { - std::pair killReply; - { - ScopedGILRelease nogil; - killReply = this->killServer(serverId, timeoutInSeconds); - } - return Wrapper::fromStdPairToPyTuple(killReply); - } - - bp::tuple existsPy(const std::string& instanceId) { - std::pair existsReply; - { - ScopedGILRelease nogil; - existsReply = this->exists(instanceId); - } - return Wrapper::fromStdPairToPyTuple(existsReply); - } - - void enableInstanceTrackingPy() { - ScopedGILRelease nogil; - enableInstanceTracking(); - } - - karabo::util::Hash getSystemInformationPy() { - ScopedGILRelease nogil; - return getSystemInformation(); - } - - karabo::util::Hash getSystemTopologyPy() { - ScopedGILRelease nogil; - return getSystemTopology(); - } - - bp::list getServersPy() { - std::vector servers; - { - ScopedGILRelease nogil; - servers = this->getServers(); - } - return Wrapper::fromStdVectorToPyList(servers); - } - - bp::list getClassesPy(const std::string& deviceServer) { - std::vector devClasses; - { - ScopedGILRelease nogil; - devClasses = this->getClasses(deviceServer); - } - return Wrapper::fromStdVectorToPyList(devClasses); - } - - bp::list getDevicesPy() { - std::vector devices; - { - ScopedGILRelease nogil; - devices = this->getDevices(); - } - return Wrapper::fromStdVectorToPyList(devices); - } - - bp::list getDevicesByServerPy(const std::string& serverId) { - std::vector devices; - { - ScopedGILRelease nogil; - devices = this->getDevices(serverId); - } - return Wrapper::fromStdVectorToPyList(devices); - } - - bp::list getPropertiesPy(const std::string& deviceId) { - std::vector props; - { - ScopedGILRelease nogil; - props = this->getProperties(deviceId); - } - return Wrapper::fromStdVectorToPyList(props); - } - - bp::list getClassPropertiesPy(const std::string& serverId, const std::string& classId) { - std::vector classProps; - { - ScopedGILRelease nogil; - classProps = this->getClassProperties(serverId, classId); - } - return Wrapper::fromStdVectorToPyList(classProps); - } - - bp::list getCurrentlySettablePropertiesPy(const std::string& instanceId) { - std::vector props; - { - ScopedGILRelease nogil; - props = this->getCurrentlySettableProperties(instanceId); - } - return Wrapper::fromStdVectorToPyList(props); - } - - bp::list getCurrentlyExecutableCommandsPy(const std::string& instanceId) { - std::vector cmds; - { - ScopedGILRelease nogil; - cmds = this->getCurrentlyExecutableCommands(instanceId); - } - return Wrapper::fromStdVectorToPyList(cmds); - } - - bp::object getPy(const std::string& instanceId, const std::string& key, const std::string& keySep = ".") { - boost::any value; - try { - ScopedGILRelease nogil; - value = this->DeviceClient::getAsAny(instanceId, key, keySep.at(0)); - } catch (...) { - KARABO_RETHROW_AS(KARABO_PARAMETER_EXCEPTION("The key \"" + key + "\" is not found in the device \"" + - instanceId + "\"")); - } - return Wrapper::toObject(value, HashWrap::isDefault(PyTypes::PYTHON_DEFAULT)); - } - - karabo::util::Hash getConfigurationPy(const std::string& instanceId) { - ScopedGILRelease nogil; - return this->DeviceClient::get(instanceId); - } - - karabo::util::Schema getDeviceSchema(const std::string& instanceId) { - ScopedGILRelease nogil; - return this->DeviceClient::getDeviceSchema(instanceId); - } - - karabo::util::Schema getDeviceSchemaNoWait(const std::string& instanceId) { - ScopedGILRelease nogil; - return this->DeviceClient::getDeviceSchemaNoWait(instanceId); - } - - karabo::util::Schema getActiveSchema(const std::string& instanceId) { - ScopedGILRelease nogil; - return this->DeviceClient::getActiveSchema(instanceId); - } - - karabo::util::Schema getClassSchema(const std::string& serverId, const std::string& classId) { - ScopedGILRelease nogil; - return this->DeviceClient::getClassSchema(serverId, classId); - } - - void registerInstanceNewMonitor(const bp::object& handler) { - this->DeviceClient::registerInstanceNewMonitor( - HandlerWrap(handler, "instanceNew monitor")); - } - - void registerInstanceUpdatedMonitor(const bp::object& handler) { - this->DeviceClient::registerInstanceUpdatedMonitor( - HandlerWrap(handler, "instanceUpdated monitor")); - } - - void registerInstanceGoneMonitor(const bp::object& handler) { - this->DeviceClient::registerInstanceGoneMonitor( - HandlerWrap(handler, "instanceGone monitor")); - } - - void registerSchemaUpdatedMonitor(const bp::object& handler) { - this->DeviceClient::registerSchemaUpdatedMonitor( - HandlerWrap(handler, "schemaUpdate monitor")); - } - - void registerDeviceMonitor(const std::string& instanceId, const bp::object& handler, - const bp::object& userData = bp::object()) { - if (userData.is_none()) { - this->DeviceClient::registerDeviceMonitor( - instanceId, - HandlerWrap(handler, "device monitor")); - } else { - this->DeviceClient::registerDeviceMonitor( - instanceId, - HandlerWrap(handler, - "device monitor 2"), - userData); // TODO: C++ stores this bp::object and might delete it without GIL protection! - } - } - - bool registerPropertyMonitor(const std::string& instanceId, const std::string& key, - const bp::object& callbackFunction, const bp::object& userData = bp::object()) { - karabo::util::Schema schema; - { - ScopedGILRelease nogil; - schema = this->getDeviceSchema(instanceId); - } - if (schema.has(key)) { - { - ScopedGILRelease nogil; - this->cacheAndGetConfiguration(instanceId); - } - - { - // TODO: Handling of callback via storage of bp::object::ptr() inside C++ treated container - // (m_propertyChangedHandlers) - // is garbage - it will at least make the Python reference counting wrong... - boost::mutex::scoped_lock lock(m_propertyChangedHandlersMutex); - if (Wrapper::hasattr(callbackFunction, "__self__")) { - const bp::object& selfObject(callbackFunction.attr("__self__")); - std::string funcName(bp::extract(callbackFunction.attr("__name__"))); - m_propertyChangedHandlers.set(instanceId + "." + key + "._function", funcName); - m_propertyChangedHandlers.set(instanceId + "." + key + "._selfObject", selfObject.ptr()); - } else { - m_propertyChangedHandlers.set(instanceId + "." + key + "._function", callbackFunction.ptr()); - } - if (!userData.is_none()) - m_propertyChangedHandlers.set(instanceId + "." + key + "._userData", userData); - } - - immortalize(instanceId); - return true; - } else { - return false; - } - } - - bool registerChannelMonitorPy(const std::string& channelName, const bp::object& dataHandler = bp::object(), - const karabo::util::Hash& inputChannelCfg = karabo::util::Hash(), - const bp::object& eosHandler = bp::object(), - const bp::object& inputHandler = bp::object(), - const bp::object& statusTracker = bp::object()) { - InputChannelHandlers handlers; - - if (!dataHandler.is_none()) { - handlers.dataHandler = InputChannelWrap::DataHandlerWrap(dataHandler, "data"); - } - if (!eosHandler.is_none()) { - handlers.eosHandler = HandlerWrap(eosHandler, "EOS"); - } - if (!inputHandler.is_none()) { - handlers.inputHandler = HandlerWrap(inputHandler, "input"); - } - if (!statusTracker.is_none()) { - handlers.statusTracker = - HandlerWrap(statusTracker, "channelStatusTracker"); - } - - ScopedGILRelease nogil; - return this->DeviceClient::registerChannelMonitor(channelName, handlers, inputChannelCfg); - } - - bool unregisterChannelMonitorPy(const std::string& channelName) { - // Need this wrapper since DeviceClient::unregisterChannelMonitor is overloaded. - // Otherwise we could us that one directly. - return this->DeviceClient::unregisterChannelMonitor(channelName); - } - - - void setDeviceMonitorIntervalPy(long int milliseconds) { - ScopedGILRelease nogil; - setDeviceMonitorInterval(milliseconds); - } - - void setPy(const std::string& instanceId, const std::string& key, const bp::object& value, - const std::string& keySep = ".", int timeout = -1) { - karabo::util::Hash tmp; - HashWrap::set(tmp, key, value, keySep); - { - ScopedGILRelease nogil; - this->set(instanceId, tmp, timeout); - } - } - - void setPy(const std::string& instanceId, const karabo::util::Hash& value, int timeout = -1) { - ScopedGILRelease nogil; - this->set(instanceId, value, timeout); - } - - void setNoWaitPy(const std::string& instanceId, const std::string& key, const bp::object& value, - const std::string& keySep = ".") { - karabo::util::Hash tmp; - HashWrap::set(tmp, key, value, keySep); - ScopedGILRelease nogil; - this->setNoWait(instanceId, tmp); - } - - void setAttributePy(const std::string& instanceId, const std::string& key, const std::string& attributeKey, - const bp::object& attributeValue, int timeoutInSeconds = -1) { - // HashWrap::set does special treatment of Hash, PyArray (i.e. numpy array), ImageData and PyDict - - // but we do not want these as attributes anyway... - boost::any attrValueAsAny; - Wrapper::toAny(attributeValue, attrValueAsAny); - - ScopedGILRelease nogil; - this->setAttribute(instanceId, key, attributeKey, attrValueAsAny, timeoutInSeconds); - } - - void executeNoWaitPy(std::string instanceId, const std::string& functionName) { - ScopedGILRelease nogil; - m_signalSlotableWrap->call(instanceId, functionName); - } - - void executePy(std::string instanceId, const std::string& functionName, int timeout = -1) { - ScopedGILRelease nogil; - execute(instanceId, functionName, timeout); - } - - bp::object getPropertyHistoryPy(const std::string& deviceId, const std::string& key, const std::string& from, - std::string to = "", unsigned int maxNumData = 0) { - std::vector propHist; - { - ScopedGILRelease nogil; - propHist = this->getPropertyHistory(deviceId, key, from, to, maxNumData); - } - return Wrapper::fromStdVectorToPyHashList(propHist); - } - - karabo::util::Hash listConfigurationFromName(const std::string& deviceId, const std::string& namePart) { - ScopedGILRelease nogil; - return this->DeviceClient::listConfigurationFromName(deviceId, namePart); - } - - karabo::util::Hash getConfigurationFromName(const std::string& deviceId, const std::string& name) { - ScopedGILRelease nogil; - return this->DeviceClient::getConfigurationFromName(deviceId, name); - } - - karabo::util::Hash getLastConfiguration(const std::string& deviceId, int priority) { - ScopedGILRelease nogil; - return this->DeviceClient::getLastConfiguration(deviceId, priority); - } - - bp::tuple saveConfigurationFromNamePy(const std::string& name, const bp::object& deviceIds, - const std::string& description, int priority, const std::string& user) { - std::pair p; - const std::vector vDeviceIds = - karathon::Wrapper::fromPyListToStdVector(deviceIds); - { - ScopedGILRelease nogil; - p = this->DeviceClient::saveConfigurationFromName(name, vDeviceIds, description, priority, user); - } - return Wrapper::fromStdPairToPyTuple(p); - } - - bp::object getConfigurationFromPastPy(const std::string& deviceId, const std::string& timePoint) { - return Wrapper::fromStdPairToPyTuple( - this->getConfigurationFromPast(deviceId, timePoint)); - } - - karabo::util::Hash getOutputChannelSchema(const std::string& deviceId, const std::string& outputChannelName) { - ScopedGILRelease nogil; - return this->DeviceClient::getOutputChannelSchema(deviceId, outputChannelName); - } - - std::vector getOutputChannelNames(const std::string& deviceId) { - ScopedGILRelease nogil; - return this->DeviceClient::getOutputChannelNames(deviceId); - } - - karabo::util::Hash::Pointer getDataSourceSchemaAsHashPy(const std::string& dataSourceId, int access) { - ScopedGILRelease nogil; - karabo::util::Hash::Pointer properties(new karabo::util::Hash()); - getDataSourceSchemaAsHash(dataSourceId, *properties, access); - return properties; - } - - boost::shared_ptr lockPy(const std::string& deviceId, bool recursive, int timeout) { - // non waiting request for lock - - if (timeout == 0) { - return boost::make_shared( - boost::make_shared(m_signalSlotable, deviceId, recursive)); - } - - // timeout was given - const int waitTime = 1; // second - int nTries = 0; - while (true) { - try { - return boost::make_shared( - boost::make_shared(m_signalSlotable, deviceId, recursive)); - - } catch (const karabo::util::LockException& e) { - if (nTries++ > timeout / waitTime && timeout != -1) { - KARABO_RETHROW; - } - // otherwise pass through and try again - boost::this_thread::sleep(boost::posix_time::seconds(waitTime)); - } - } - } - - - private: - void notifyPropertyChangedMonitors(const karabo::util::Hash& hash, const std::string& instanceId) { - karabo::util::Hash registeredMonitors; - { - boost::mutex::scoped_lock lock(m_propertyChangedHandlersMutex); - if (m_propertyChangedHandlers.has(instanceId)) { - registeredMonitors = m_propertyChangedHandlers.get(instanceId); - } - } - if (!registeredMonitors.empty()) { - this->callMonitor(instanceId, registeredMonitors, hash); - } - } - - void callMonitor(const std::string& instanceId, const karabo::util::Hash& registered, - const karabo::util::Hash& current, std::string path = "") { - for (karabo::util::Hash::const_iterator it = current.begin(); it != current.end(); ++it) { - std::string currentPath = it->getKey(); - if (!path.empty()) currentPath = path + "." + it->getKey(); - if (registered.has(currentPath + "._function")) { - karabo::util::Timestamp t; - try { - t = karabo::util::Timestamp::fromHashAttributes(it->getAttributes()); - } catch (...) { - KARABO_LOG_FRAMEWORK_WARN << "No timestamp information given on \"" << it->getKey() << "/"; - } - const karabo::util::Hash& entry = registered.get(currentPath); - boost::optional nodeFunc = entry.find("_function"); - boost::optional nodeSelfObject = entry.find("_selfObject"); - boost::optional nodeData = entry.find("_userData"); - { - try { - if (nodeSelfObject) { - if (nodeData) { - ScopedGILAcquire gil; - bp::call_method(nodeSelfObject->getValue(), - nodeFunc->getValue().c_str(), instanceId, - currentPath, Wrapper::toObject(it->getValueAsAny()), t, - nodeData->getValue()); - } else { - ScopedGILAcquire gil; - bp::call_method(nodeSelfObject->getValue(), - nodeFunc->getValue().c_str(), instanceId, - currentPath, Wrapper::toObject(it->getValueAsAny()), t); - } - } else { - if (nodeData) { - ScopedGILAcquire gil; - bp::call(nodeFunc->getValue(), instanceId, currentPath, - Wrapper::toObject(it->getValueAsAny()), t, - nodeData->getValue()); - } else { - ScopedGILAcquire gil; - bp::call(nodeFunc->getValue(), instanceId, currentPath, - Wrapper::toObject(it->getValueAsAny()), t); - } - } - - } catch (const karabo::util::Exception& e) { - std::cout << e.detailedMsg(); - } - } - } - if (it->is()) - callMonitor(instanceId, registered, it->getValue(), currentPath); - } - } - - private: // members - bool m_isVerbose; - - boost::shared_ptr m_signalSlotableWrap; - }; -} // namespace karathon - -#endif /* KARATHON_DEVCOM_HH */ diff --git a/src/karathon/DimsWrap.hh b/src/karathon/DimsWrap.hh deleted file mode 100644 index 586862f77f..0000000000 --- a/src/karathon/DimsWrap.hh +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef KARATHON_DIMSWRAP_HH -#define KARATHON_DIMSWRAP_HH - -#include -#include -#include - - -namespace karathon { - - class DimsWrap : public karabo::util::Dims { - public: - DimsWrap() : karabo::util::Dims() {} - - DimsWrap(const std::vector& vec) : karabo::util::Dims(vec) {} - - DimsWrap(const bp::list& list) : karabo::util::Dims(Wrapper::fromPyListToStdVector(list)) {} - - DimsWrap(const bp::tuple& list) - : karabo::util::Dims(Wrapper::fromPyTupleToStdVector(list)) {} - - DimsWrap(unsigned long long xSize) : karabo::util::Dims(xSize) {} - - DimsWrap(unsigned long long xSize, unsigned long long ySize) : karabo::util::Dims(xSize, ySize) {} - - DimsWrap(unsigned long long xSize, unsigned long long ySize, unsigned long long zSize) - : karabo::util::Dims(xSize, ySize, zSize) {} - - DimsWrap(unsigned long long x1Size, unsigned long long x2Size, unsigned long long x3Size, - unsigned long long x4Size) - : karabo::util::Dims(x1Size, x2Size, x3Size, x4Size) {} - - bp::object toVectorPy() { - return Wrapper::fromStdVectorToPyList(this->toVector()); - } - - bp::object toArrayPy() { - return Wrapper::fromStdVectorToPyArray(this->toVector()); - } - - private: - std::vector convertFromListToVector(bp::list& dims) { - std::vector vec(bp::len(dims), 0); - for (int i = 0; i < bp::len(dims); ++i) { - vec[i] = bp::extract(dims[i]); - } - return vec; - } - }; - -} // namespace karathon - - -#endif /* KARATHON_DIMSWRAP_HH */ diff --git a/src/karathon/FromNumpy.cc b/src/karathon/FromNumpy.cc deleted file mode 100644 index 66ae53c74d..0000000000 --- a/src/karathon/FromNumpy.cc +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: FromNumpy.cc - * Author: - * - * Created on May 23, 2014 6:34 PM - * - */ - -#include "FromNumpy.hh" - -#include - -#include "Wrapper.hh" - -namespace karathon { - - - FromNumpy::FromNumpy() { - // #define _KARABO_HELPER_MACRO(fromType, refType) (fromType, karabo::util::Types::refType) -#define _KARABO_HELPER_MACRO(fromType, refType) \ - { fromType, karabo::util::Types::refType } - - if (sizeof(unsigned long) == sizeof(unsigned int)) { // 32 bit CPU - _typeInfoMap = {_KARABO_HELPER_MACRO(NPY_BOOL, BOOL), _KARABO_HELPER_MACRO(NPY_BYTE, INT8), - _KARABO_HELPER_MACRO(NPY_UBYTE, UINT8), _KARABO_HELPER_MACRO(NPY_SHORT, INT16), - _KARABO_HELPER_MACRO(NPY_USHORT, UINT16), _KARABO_HELPER_MACRO(NPY_INT, INT32), - _KARABO_HELPER_MACRO(NPY_UINT, UINT32), _KARABO_HELPER_MACRO(NPY_LONG, INT32), - _KARABO_HELPER_MACRO(NPY_ULONG, UINT32), _KARABO_HELPER_MACRO(NPY_LONGLONG, INT64), - _KARABO_HELPER_MACRO(NPY_ULONGLONG, UINT64), _KARABO_HELPER_MACRO(NPY_FLOAT, FLOAT), - _KARABO_HELPER_MACRO(NPY_DOUBLE, DOUBLE)}; - } else { // 64 bit CPU - _typeInfoMap = {_KARABO_HELPER_MACRO(NPY_BOOL, BOOL), _KARABO_HELPER_MACRO(NPY_BYTE, INT8), - _KARABO_HELPER_MACRO(NPY_UBYTE, UINT8), _KARABO_HELPER_MACRO(NPY_SHORT, INT16), - _KARABO_HELPER_MACRO(NPY_USHORT, UINT16), _KARABO_HELPER_MACRO(NPY_INT, INT32), - _KARABO_HELPER_MACRO(NPY_UINT, UINT32), _KARABO_HELPER_MACRO(NPY_LONG, INT64), - _KARABO_HELPER_MACRO(NPY_ULONG, UINT64), _KARABO_HELPER_MACRO(NPY_LONGLONG, INT64), - _KARABO_HELPER_MACRO(NPY_ULONGLONG, UINT64), _KARABO_HELPER_MACRO(NPY_FLOAT, FLOAT), - _KARABO_HELPER_MACRO(NPY_DOUBLE, DOUBLE)}; - } -#undef _KARABO_HELPER_MACRO - } -} // namespace karathon diff --git a/src/karathon/FromNumpy.hh b/src/karathon/FromNumpy.hh deleted file mode 100644 index 02a6e7e6c8..0000000000 --- a/src/karathon/FromNumpy.hh +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: FromNumpy.hh - * Author: - * - * Created on May 23, 2014 6:34 PM - * - */ - -#ifndef KARABO_UTIL_FROMNUMPY_HH -#define KARABO_UTIL_FROMNUMPY_HH - -#include -#include -#include - -namespace karathon { - - class FromNumpy { - public: - typedef int ArgumentType; - - static karabo::util::Types::ReferenceType from(const ArgumentType& type) { - TypeInfoMap::const_iterator it = FromNumpy::init()._typeInfoMap.find(type); - if (it == FromNumpy::init()._typeInfoMap.end()) - throw KARABO_PARAMETER_EXCEPTION("Requested argument type not registered"); - return it->second; - } - - private: - FromNumpy(); - - FromNumpy(const FromNumpy&){}; - - virtual ~FromNumpy(){}; - - static FromNumpy& init() { - static FromNumpy singleInstance; - return singleInstance; - } - - - typedef std::map TypeInfoMap; - - TypeInfoMap _typeInfoMap; - }; - -} // namespace karathon - -#endif diff --git a/src/karathon/HashWrap.cc b/src/karathon/HashWrap.cc deleted file mode 100644 index 4d152adbf7..0000000000 --- a/src/karathon/HashWrap.cc +++ /dev/null @@ -1,735 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include "HashWrap.hh" - -#include // std::copy -#include -#include -#include -#include -#include -#include // std::cout, std::endl -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Wrapper.hh" - -namespace bp = boost::python; - -using std::string; -using std::vector; - -namespace karabo { - namespace util { - - - template <> - karabo::util::Hash::Hash(const std::string& key, const bp::object& value) { - karathon::HashWrap::set(*this, key, value); - } - - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2) { - karathon::HashWrap::set(*this, key1, value1); - karathon::HashWrap::set(*this, key2, value2); - } - - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3) { - karathon::HashWrap::set(*this, key1, value1); - karathon::HashWrap::set(*this, key2, value2); - karathon::HashWrap::set(*this, key3, value3); - } - - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4) { - karathon::HashWrap::set(*this, key1, value1); - karathon::HashWrap::set(*this, key2, value2); - karathon::HashWrap::set(*this, key3, value3); - karathon::HashWrap::set(*this, key4, value4); - } - - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4, const std::string& key5, - const bp::object& value5) { - karathon::HashWrap::set(*this, key1, value1); - karathon::HashWrap::set(*this, key2, value2); - karathon::HashWrap::set(*this, key3, value3); - karathon::HashWrap::set(*this, key4, value4); - karathon::HashWrap::set(*this, key5, value5); - } - - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4, const std::string& key5, - const bp::object& value5, const std::string& key6, const bp::object& value6) { - karathon::HashWrap::set(*this, key1, value1); - karathon::HashWrap::set(*this, key2, value2); - karathon::HashWrap::set(*this, key3, value3); - karathon::HashWrap::set(*this, key4, value4); - karathon::HashWrap::set(*this, key5, value5); - karathon::HashWrap::set(*this, key6, value6); - } - } // namespace util -} // namespace karabo - -namespace karathon { - - - void HashWrap::setPyListAsStdVector(karabo::util::Hash& self, const std::string& key, const bp::object& list, - bp::ssize_t size, const char sep) { - // elements of our vectors require to be of the same type - bp::object list0 = list[0]; - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - } else if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - } else if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - - } else if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - - } else if (PyBool_Check(list0.ptr())) { - std::deque v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - - // } else if (PyDict_Check(list0.ptr())) { - // std::vector v(size); - // for (bp::ssize_t i = 0; i < size; ++i) { - // bp::dict d = bp::extract (list[i]); - // fromPyDictToHash(v[i], d, sep); - // } - // self.set(key, v, sep); - - } else if (bp::extract(list[0]).check()) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(list[i]); - } - self.set(key, v, sep); - - } else { - throw KARABO_PYTHON_EXCEPTION("Failed to convert inner type of python list"); - } - } - - - void HashWrap::setPyStrAsStdVector(karabo::util::Hash& self, const std::string& key, const bp::object& pystr, - const char sep) { - if (!PyUnicode_Check(pystr.ptr())) - throw KARABO_PYTHON_EXCEPTION("Failed to convert python string to vector of unsigned char "); - const std::string& stdstr = bp::extract(pystr); - self.set(key, std::vector(stdstr.begin(), stdstr.end()), sep); - } - - - const karabo::util::Hash& HashWrap::setPyDictAsHash(karabo::util::Hash& self, const bp::dict& dictionary, - const char sep) { - std::string separator(1, sep); - bp::list keys(dictionary.keys()); - for (bp::ssize_t i = 0; i < bp::len(keys); i++) { - const bp::object& obj = dictionary[keys[i]]; - if (PyDict_Check(obj.ptr())) { - const bp::dict& dictobj = bp::extract(obj); - karabo::util::Hash h; - self.set(bp::extract(keys[i]), setPyDictAsHash(h, dictobj, sep), sep); - } else { - set(self, bp::extract(keys[i]), obj, separator); - } - } - return self; - } - - - bp::object HashWrap::empty(const karabo::util::Hash& self) { - return bp::object(self.empty() ? 1 : 0); - } - - - void HashWrap::getKeys(const karabo::util::Hash& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - std::vector v; - self.getKeys(v); - for (size_t i = 0; i < v.size(); i++) obj.attr("append")(bp::object(v[i])); - return; - } - throw KARABO_PYTHON_EXCEPTION("Python type should be 'list'"); - } - - - bp::list HashWrap::keys(const karabo::util::Hash& self) { - bp::list l; - getKeys(self, l); - return l; - } - - - void HashWrap::getPaths(const karabo::util::Hash& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - std::vector v; - self.getPaths(v); - for (size_t i = 0; i < v.size(); i++) obj.attr("append")(bp::object(v[i])); - return; - } - throw KARABO_PYTHON_EXCEPTION("Python type should be 'list'"); - } - - - bp::list HashWrap::paths(const karabo::util::Hash& self) { - bp::list l; - getPaths(self, l); - return l; - } - - - bp::object HashWrap::getValues(const karabo::util::Hash& self) { - bp::list t; - for (karabo::util::Hash::const_iterator it = self.begin(); it != self.end(); it++) - t.append(Wrapper::toObject(it->getValueAsAny(), HashWrap::try_to_use_numpy)); - return t; - } - - - bp::object HashWrap::get(const karabo::util::Hash& self, const std::string& path, const std::string& separator, - const bp::object& default_return) { - // This implements the standard Python dictionary behavior for get() - if (!self.has(path, separator.at(0))) { - return default_return; - } - - return HashWrap::getRef(const_cast(self), bp::object(path), separator); - } - - - bp::object HashWrap::getAs(const karabo::util::Hash& self, const std::string& path, - const PyTypes::ReferenceType& type, const std::string& separator) { - using namespace karabo::util; - Types::ReferenceType srcType = self.getType(path, separator.at(0)); - switch (type) { - case PyTypes::BOOL: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::CHAR: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::INT8: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::UINT8: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::INT16: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::UINT16: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::INT32: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::UINT32: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::INT64: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::UINT64: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::FLOAT: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::DOUBLE: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::STRING: - return bp::object(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_BOOL: { - switch (srcType) { - case Types::STRING: { - string s = self.get(path, separator.at(0)); - vector vv; - for (size_t i = 0; i < s.size(); i++) { - for (size_t j = 0; j < 8; j++) vv.push_back(s[i] & (1 << (7 - j)) ? true : false); - } - return Wrapper::fromStdVectorToPyArray(vv); - } - default: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - } - } - case PyTypes::VECTOR_CHAR: { - switch (srcType) { - case Types::STRING: { - const string& s = self.get(path, separator.at(0)); - vector vec(s.begin(), s.end()); - return Wrapper::fromStdVectorToPyByteArray(vec); - } - default: - return Wrapper::fromStdVectorToPyByteArray( - self.getAs(path, separator.at(0))); - } - } - case PyTypes::VECTOR_INT8: { - switch (srcType) { - case Types::STRING: { - const string& s = self.get(path, separator.at(0)); - vector vec(s.begin(), s.end()); - return Wrapper::fromStdVectorToPyByteArray(vec); - } - default: - return Wrapper::fromStdVectorToPyByteArray( - self.getAs(path, separator.at(0))); - } - } - case PyTypes::VECTOR_UINT8: { - switch (srcType) { - case Types::STRING: { - const string& s = self.get(path, separator.at(0)); - vector vec(s.begin(), s.end()); - return Wrapper::fromStdVectorToPyByteArray(vec); - } - default: - return Wrapper::fromStdVectorToPyByteArray( - self.getAs(path, separator.at(0))); - } - } - case PyTypes::VECTOR_INT16: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_UINT16: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_INT32: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_UINT32: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_INT64: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_UINT64: - return Wrapper::fromStdVectorToPyArray( - self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_FLOAT: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_DOUBLE: - return Wrapper::fromStdVectorToPyArray(self.getAs(path, separator.at(0))); - case PyTypes::VECTOR_COMPLEX_FLOAT: - return Wrapper::fromStdVectorToPyArray( - self.getAs, std::vector>(path, separator.at(0))); - case PyTypes::VECTOR_COMPLEX_DOUBLE: - return Wrapper::fromStdVectorToPyArray( - self.getAs, std::vector>(path, separator.at(0))); - // case PyTypes::HASH: - // return bp::object(self.getAs(path, separator.at(0))); - // case PyTypes::VECTOR_HASH: - // return Wrapper::fromStdVectorToPyList(self.getAs(path, separator.at(0))); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - - bp::object HashWrap::getNode(karabo::util::Hash& self, const std::string& path, const std::string& separator) { - using namespace karabo::util; - Hash::Node& nodeRef = self.getNode(path, separator.at(0)); - boost::optional node(nodeRef); - return bp::object(boost::shared_ptr(&(*node), null_deleter())); - } - - - bp::object HashWrap::setNode(karabo::util::Hash& self, const bp::object& node) { - if (bp::extract(node).check()) { - return bp::object(self.setNode(bp::extract(node))); - } - throw KARABO_PYTHON_EXCEPTION("Failed to extract C++ 'const Hash::Node&' from python object"); - } - - - void HashWrap::set(karabo::util::Hash& self, const std::string& key, const bp::object& obj, - const std::string& separator) { - using namespace karabo::util; - if (bp::extract(obj).check()) { - const Hash& h = bp::extract(obj); - self.set(key, h, separator.at(0)); - return; - } - if (PyArray_Check(obj.ptr())) { - PyArrayObject* pyarr = reinterpret_cast(obj.ptr()); - const NDArray arr = Wrapper::fromPyArrayToNDArray(pyarr); - self.set(key, arr, separator.at(0)); - return; - } - if (bp::extract(obj).check()) { - const karabo::xms::ImageData& img = bp::extract(obj); - self.set(key, img, separator.at(0)); - return; - } - if (PyDict_Check(obj.ptr())) { - const bp::dict& d = bp::extract(obj); - Hash h; - self.set(key, setPyDictAsHash(h, d, separator.at(0)), separator.at(0)); - return; - } - boost::any any; - Wrapper::toAny(obj, any); - self.set(key, any, separator.at(0)); - } - - - void HashWrap::setAs(karabo::util::Hash& self, const std::string& key, const bp::object& value, - const bp::object& o_type, const std::string& separator) { - using namespace karabo::util; - set(self, key, value, separator); - Hash::Node& node = self.getNode(key, separator.at(0)); - Types::ReferenceType cppType; - if (bp::extract(o_type).check()) { - std::string s_type = bp::extract(o_type); - cppType = Types::from(s_type); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - cppType = PyTypes::to(type); - } - node.setType(cppType); - } - - - bool HashWrap::erase(karabo::util::Hash& self, const bp::object& keyObj, const std::string& separator) { - const char sep = separator.at(0); - std::string key; - if (bp::extract(keyObj).check()) { - key = bp::extract(keyObj); - } else { - throw KARABO_PYTHON_EXCEPTION("Currently values can only be retrieved by string keys"); - } - return self.erase(key, sep); - } - - - void HashWrap::erasePath(karabo::util::Hash& self, const bp::object& keyObj, const std::string& separator) { - const char sep = separator.at(0); - std::string key; - if (bp::extract(keyObj).check()) { - key = bp::extract(keyObj); - } else { - throw KARABO_PYTHON_EXCEPTION("Currently values can only be retrieved by string keys"); - } - self.erasePath(key, sep); - } - - - bool HashWrap::has(karabo::util::Hash& self, const std::string& key, const std::string& separator) { - return self.has(key, separator.at(0)); - } - - - bool HashWrap::is(karabo::util::Hash& self, const std::string& path, const PyTypes::ReferenceType& type, - const std::string& separator) { - if (type < PyTypes::LAST_CPP_TYPE) return type == PyTypes::from(self.getType(path, separator.at(0))); - return false; - } - - - void HashWrap::flatten(const karabo::util::Hash& self, karabo::util::Hash& flat, const std::string& separator) { - self.flatten(flat, separator.at(0)); - } - - - void HashWrap::unflatten(const karabo::util::Hash& self, karabo::util::Hash& tree, const std::string& separator) { - self.unflatten(tree, separator.at(0)); - } - - - bp::object HashWrap::getType(const karabo::util::Hash& self, const std::string& path, - const std::string& separator) { - const char sep = separator.at(0); - PyTypes::ReferenceType type = static_cast(self.getType(path, sep)); - return bp::object(type); - } - - - bool HashWrap::hasAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const std::string& separator) { - return self.hasAttribute(path, attribute, separator.at(0)); - } - - - bp::object HashWrap::getAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const std::string& separator) { - return Wrapper::toObject(self.getAttributeAsAny(path, attribute, separator.at(0)), HashWrap::try_to_use_numpy); - } - - - bp::object HashWrap::getAttributeAs(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const PyTypes::ReferenceType& type, const std::string& separator) { - using namespace karabo::util; - switch (type) { - case PyTypes::BOOL: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::CHAR: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::INT8: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::UINT8: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::INT16: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::UINT16: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::INT32: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::UINT32: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::INT64: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::UINT64: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::FLOAT: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::DOUBLE: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::STRING: - return bp::object(self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::VECTOR_BOOL: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_CHAR: - return Wrapper::fromStdVectorToPyByteArray( - self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::VECTOR_INT8: - return Wrapper::fromStdVectorToPyByteArray( - self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::VECTOR_UINT8: - return Wrapper::fromStdVectorToPyByteArray( - self.getAttributeAs(path, attribute, separator.at(0))); - case PyTypes::VECTOR_INT16: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_UINT16: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_INT32: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_UINT32: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_INT64: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_UINT64: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_FLOAT: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_DOUBLE: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_COMPLEX_FLOAT: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs, std::vector>(path, attribute, separator.at(0)), false); - case PyTypes::VECTOR_COMPLEX_DOUBLE: - return Wrapper::fromStdVectorToPyArray( - self.getAttributeAs, std::vector>(path, attribute, separator.at(0)), false); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - - const karabo::util::Hash::Attributes& HashWrap::getAttributes(karabo::util::Hash& self, const std::string& path, - const std::string& separator) { - return static_cast(self.getAttributes(path, separator.at(0))); - } - - - bp::object HashWrap::copyAttributes(karabo::util::Hash& self, const std::string& path, - const std::string& separator) { - return bp::object(self.getAttributes(path, separator.at(0))); - } - - - void HashWrap::setAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const bp::object& value, const std::string& separator) { - boost::any any; - Wrapper::toAny(value, any); - self.setAttribute(path, attribute, any, separator.at(0)); - } - - - void HashWrap::setAttributes(karabo::util::Hash& self, const std::string& path, const bp::object& attributes, - const std::string& separator) { - if (bp::extract(attributes).check()) { - self.setAttributes(path, bp::extract(attributes), separator.at(0)); - return; - } - throw KARABO_PYTHON_EXCEPTION("Python object contains not a C++ 'Hash::Attributes' type"); - } - - - void HashWrap::merge(karabo::util::Hash& self, const karabo::util::Hash& other, - const karabo::util::Hash::MergePolicy policy, const bp::object& selectedPaths, - const std::string& separator) { - std::set selectedPathsCpp; - if (selectedPaths.ptr() != Py_None) { - bp::stl_input_iterator pathsBegin(selectedPaths), pathsEnd; - selectedPathsCpp.insert(pathsBegin, pathsEnd); - } - self.merge(other, policy, selectedPathsCpp, separator.at(0)); - } - - - boost::shared_ptr HashWrap::find(karabo::util::Hash& self, const std::string& path, - const std::string& separator) { - boost::optional node = self.find(path, separator.at(0)); - - if (!node) return boost::shared_ptr(); - // Wrapping the pointer to the existing memory location with null deleter - return boost::shared_ptr(&node.get(), null_deleter()); - } - - - bp::object HashWrap::getRef(karabo::util::Hash& self, const bp::object& obj, const std::string& sep) { - using namespace karabo::util; - if (bp::extract(obj).check()) { - Hash::Node& node = bp::extract(obj); - if (node.getType() == Types::HASH) { - return Wrapper::toCustomObject(node); - } - return Wrapper::toObject(node.getValueAsAny(), HashWrap::try_to_use_numpy); - } else if (bp::extract(obj).check()) { - std::string path = bp::extract(obj); - Hash::Node& node = self.getNode(path, sep.at(0)); - if (node.getType() == karabo::util::Types::HASH) { - return Wrapper::toCustomObject(node); - } - if (node.getType() == Types::VECTOR_HASH) { - std::vector* vhp = &node.getValue >(); - boost::shared_ptr > vhash = - boost::shared_ptr >(vhp, null_deleter()); - return bp::object(vhash); - } - return Wrapper::toObject(node.getValueAsAny(), HashWrap::try_to_use_numpy); - } - throw KARABO_PYTHON_EXCEPTION("Invalid type for Hash index. The type should be 'Node' or 'str'!"); - } - - - bool similarWrap(const bp::object& left, const bp::object& right) { - if (bp::extract(left).check() && bp::extract(right).check()) { - const karabo::util::Hash& lhash = bp::extract(left); - const karabo::util::Hash& rhash = bp::extract(right); - return karabo::util::similar(lhash, rhash); - } - - if (bp::extract(left).check() && - bp::extract(right).check()) { - const karabo::util::Hash::Node& lnode = bp::extract(left); - const karabo::util::Hash::Node& rnode = bp::extract(right); - return karabo::util::similar(lnode, rnode); - } - - if (PyList_Check(left.ptr()) && PyList_Check(right.ptr())) { - bp::object left0 = left[0]; - bp::object right0 = right[0]; - bp::ssize_t lsize = bp::len(left); - bp::ssize_t rsize = bp::len(right); - if (lsize == rsize) { - bp::ssize_t size = lsize; // rsize == lsize - if (bp::extract(left0).check() && bp::extract(right0).check()) { - std::vector vleft(size); - std::vector vright(size); - for (bp::ssize_t i = 0; i < size; i++) { - vleft[i] = bp::extract(left[i]); - vright[i] = bp::extract(right[i]); - } - return karabo::util::similar(vleft, vright); - } - } - } - - if (bp::extract(left).check() && bp::extract(right).check()) { - const karabo::util::Schema& l = bp::extract(left); - const karabo::util::Schema& r = bp::extract(right); - return karabo::util::similar(l, r); - } - - return false; - } - - - bool fullyEqualWrap(const bp::object& left, const bp::object& right, const bp::object& orderMatters) { - bp::extract leftExtracted(left); - if (!leftExtracted.check()) return false; - - bp::extract rightExtracted(right); - if (!rightExtracted.check()) return false; - - const karabo::util::Hash& lhash = leftExtracted; - const karabo::util::Hash& rhash = rightExtracted; - return lhash.fullyEquals(rhash, bp::extract(orderMatters)); - } - - void HashWrap::setDefault(const PyTypes::ReferenceType& type) { - if (type == PyTypes::PYTHON_DEFAULT) try_to_use_numpy = false; - else if (type == PyTypes::NUMPY_DEFAULT) try_to_use_numpy = true; - else throw KARABO_PYTHON_EXCEPTION("Unsupported default type: use either Types.NUMPY or Types.PYTHON"); - } - - - bool HashWrap::isDefault(const PyTypes::ReferenceType& type) { - if (type == PyTypes::PYTHON_DEFAULT && !try_to_use_numpy) return true; - else if (type == PyTypes::NUMPY_DEFAULT && try_to_use_numpy) return true; - return false; - } -} // namespace karathon - -bool karathon::HashWrap::try_to_use_numpy = false; diff --git a/src/karathon/HashWrap.hh b/src/karathon/HashWrap.hh deleted file mode 100644 index a18698966e..0000000000 --- a/src/karathon/HashWrap.hh +++ /dev/null @@ -1,207 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* $Id$ - * - * Author: - * - * Created on March 16, 2012, 12:43 PM - */ - -#ifndef KARATHON_HASHWRAP_HH -#define KARATHON_HASHWRAP_HH - -#include -#include - -#include "Wrapper.hh" - -namespace bp = boost::python; - - -namespace karathon { - - class HashWrap { - struct null_deleter { - void operator()(void const*) const {} - }; - - static bool try_to_use_numpy; - - static void setPyListAsStdVector(karabo::util::Hash& self, const std::string& key, const bp::object& list, - bp::ssize_t size, const char sep); - - static void setPyStrAsStdVector(karabo::util::Hash& self, const std::string& key, const bp::object& pystr, - const char sep); - - public: - static const karabo::util::Hash& setPyDictAsHash(karabo::util::Hash& self, const bp::dict& dictionary, - const char sep); - - static bp::object empty(const karabo::util::Hash& self); - - static void getKeys(const karabo::util::Hash& self, const bp::object& obj); - - static bp::list keys(const karabo::util::Hash& self); - - static void getPaths(const karabo::util::Hash& self, const bp::object& obj); - - static bp::list paths(const karabo::util::Hash& self); - - static bp::object getValues(const karabo::util::Hash& self); - - static bp::object get(const karabo::util::Hash& self, const std::string& path, - const std::string& separator = ".", const bp::object& default_return = bp::object()); - - static karabo::util::Hash copy(const karabo::util::Hash& self) { - return self; - } - - static bp::object getAs(const karabo::util::Hash& self, const std::string& path, - const PyTypes::ReferenceType& type, const std::string& separator = "."); - - static bp::object getNode(karabo::util::Hash& self, const std::string& path, - const std::string& separator = "."); - - static bp::object setNode(karabo::util::Hash& self, const bp::object& node); - - static void set(karabo::util::Hash& self, const std::string& key, const bp::object& obj, - const std::string& separator = "."); - - static void setAs(karabo::util::Hash& self, const std::string& key, const bp::object& obj, - const bp::object& type, const std::string& separator = "."); - - static bool erase(karabo::util::Hash& self, const bp::object& keyObj, const std::string& separator = "."); - - static void erasePath(karabo::util::Hash& self, const bp::object& keyObj, const std::string& separator = "."); - - static bool has(karabo::util::Hash& self, const std::string& key, const std::string& separator = "."); - - static bool is(karabo::util::Hash& self, const std::string& path, const PyTypes::ReferenceType& type, - const std::string& separator = "."); - - static void flatten(const karabo::util::Hash& self, karabo::util::Hash& flat, - const std::string& separator = "."); - - static void unflatten(const karabo::util::Hash& self, karabo::util::Hash& tree, - const std::string& separator = "."); - - static bp::object getType(const karabo::util::Hash& self, const std::string& path, - const std::string& separator = "."); - - static bool hasAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const std::string& separator = "."); - - static bp::object getAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const std::string& separator = "."); - - static bp::object getAttributeAs(karabo::util::Hash& self, const std::string& path, - const std::string& attribute, const PyTypes::ReferenceType& type, - const std::string& separator = "."); - - static const karabo::util::Hash::Attributes& getAttributes(karabo::util::Hash& self, const std::string& path, - const std::string& separator = "."); - - static bp::object copyAttributes(karabo::util::Hash& self, const std::string& path, - const std::string& separator = "."); - - static void setAttribute(karabo::util::Hash& self, const std::string& path, const std::string& attribute, - const bp::object& value, const std::string& separator = "."); - - static void setAttributes(karabo::util::Hash& self, const std::string& path, const bp::object& attributes, - const std::string& separator = "."); - - static void merge(karabo::util::Hash& self, const karabo::util::Hash& other, - const karabo::util::Hash::MergePolicy policy, const bp::object& selectedPaths, - const std::string& separator); - - static boost::shared_ptr find(karabo::util::Hash& self, const std::string& path, - const std::string& separator = "."); - - static bp::object getRef(karabo::util::Hash& self, const bp::object& obj, const std::string& sep = "."); - - static void setDefault(const PyTypes::ReferenceType& type); - - static bool isDefault(const PyTypes::ReferenceType& type); - }; - - bool similarWrap(const bp::object& left, const bp::object& right); - - bool fullyEqualWrap(const bp::object& left, const bp::object& right, const bp::object& orderMatters); - - // implementation details, users never invoke these directly - namespace detail { - - inline void packPy_r(karabo::util::Hash& hash, char i) {} - - template - inline void packPy_r(karabo::util::Hash& hash, char i, const Tfirst& first, const Trest&... rest) { - char name[4] = "a "; - name[1] = i; - // Besides the following line, 'packPy_r' is identical to the C++ version 'karabo::util::pack_r'. - HashWrap::set(hash, name, first); - detail::packPy_r(hash, i + 1, rest...); - } - } // namespace detail - - /** - * Pack the parameters into a hash for transport over the network. - * @param hash Will be filled with keys a1, a2, etc. and associated values - * @param args Any type and number of arguments to associated to hash keys - */ - template - inline void packPy(karabo::util::Hash& hash, const Ts&... args) { - detail::packPy_r(hash, '1', args...); - } -} // namespace karathon - -// Define 'bp::object' specialization for templated constructors of Hash class - -namespace karabo { - namespace util { - - template <> - karabo::util::Hash::Hash(const std::string& key, const bp::object& value); - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2); - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3); - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4); - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4, const std::string& key5, - const bp::object& value5); - - template <> - karabo::util::Hash::Hash(const std::string& key1, const bp::object& value1, const std::string& key2, - const bp::object& value2, const std::string& key3, const bp::object& value3, - const std::string& key4, const bp::object& value4, const std::string& key5, - const bp::object& value5, const std::string& key6, const bp::object& value6); - } // namespace util -} // namespace karabo - -#endif /* KARATHON_HASHWRAP_HH */ diff --git a/src/karathon/NodeWrap.hh b/src/karathon/NodeWrap.hh deleted file mode 100644 index 73640fea42..0000000000 --- a/src/karathon/NodeWrap.hh +++ /dev/null @@ -1,263 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ElementWrap.hh - * Author: Sergey Esenov - * - * Created on March 17, 2013, 6:29 PM - */ - -#ifndef ELEMENTWRAP_HH -#define ELEMENTWRAP_HH - -#include -#include -#include -#include - -#include "Wrapper.hh" - -namespace bp = boost::python; - -namespace karathon { - - class NodeWrap { - struct null_deleter { - void operator()(void const*) const {} - }; - - public: - typedef boost::shared_ptr Pointer; - - static bp::object getKey(const Pointer& node) { - return bp::object(node->getKey()); - } - - static void setValue(const Pointer& node, const bp::object& obj) { - boost::any any; - Wrapper::toAny(obj, any); - node->setValue(any); - } - - static bp::object getValue(const Pointer& node) { - using namespace karabo::util; - boost::any& a = node->getValueAsAny(); - // handle Hash differently returning reference to Hash - if (a.type() == typeid(Hash)) { - Hash& hash = boost::any_cast(a); - boost::shared_ptr p(&hash, null_deleter()); - return bp::object(p); - } - return Wrapper::toObject(a); - } - - static bp::object getValueAs(const Pointer& node, const bp::object& o_type) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - reftype = Types::from(type); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - reftype = PyTypes::to(type); - } - switch (reftype) { - case Types::BOOL: - return bp::object(node->getValueAs()); - case Types::CHAR: - return bp::object(node->getValueAs()); - case Types::INT8: - return bp::object(node->getValueAs()); - case Types::UINT8: - return bp::object(node->getValueAs()); - case Types::INT16: - return bp::object(node->getValueAs()); - case Types::UINT16: - return bp::object(node->getValueAs()); - case Types::INT32: - return bp::object(node->getValueAs()); - case Types::UINT32: - return bp::object(node->getValueAs()); - case Types::INT64: - return bp::object(node->getValueAs()); - case Types::UINT64: - return bp::object(node->getValueAs()); - case Types::FLOAT: - return bp::object(node->getValueAs()); - case Types::DOUBLE: - return bp::object(node->getValueAs()); - case Types::STRING: - return bp::object(node->getValueAs()); - case Types::VECTOR_BOOL: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_CHAR: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_INT8: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_UINT8: - return Wrapper::fromStdVectorToPyByteArray(node->getValueAs()); - case Types::VECTOR_INT16: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT16: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_INT32: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT32: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_INT64: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - case Types::VECTOR_UINT64: - return Wrapper::fromStdVectorToPyArray(node->getValueAs()); - // case Types::HASH: - // return bp::object(node->getValueAs()); - // case Types::VECTOR_HASH: - // return Wrapper::fromStdVectorToPyList(node->getValueAs()); - - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - static void setAttribute(const Pointer& node, const std::string& key, const bp::object& obj) { - boost::any value; - Wrapper::toAny(obj, value); - node->setAttribute(key, value); - } - - static bp::object getAttribute(const Pointer& node, const std::string& key) { - return Wrapper::toObject(node->getAttributeAsAny(key)); - } - - static bp::object getAttributeAs(const Pointer& node, const std::string& key, const bp::object& o_type) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - reftype = Types::from(type); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - reftype = PyTypes::to(type); - } - - switch (reftype) { - case Types::BOOL: - return bp::object(node->getAttributeAs(key)); - case Types::CHAR: - return bp::object(node->getAttributeAs(key)); - case Types::INT8: - return bp::object(node->getAttributeAs(key)); - case Types::UINT8: - return bp::object(node->getAttributeAs(key)); - case Types::INT16: - return bp::object(node->getAttributeAs(key)); - case Types::UINT16: - return bp::object(node->getAttributeAs(key)); - case Types::INT32: - return bp::object(node->getAttributeAs(key)); - case Types::UINT32: - return bp::object(node->getAttributeAs(key)); - case Types::INT64: - return bp::object(node->getAttributeAs(key)); - case Types::UINT64: - return bp::object(node->getAttributeAs(key)); - case Types::FLOAT: - return bp::object(node->getAttributeAs(key)); - case Types::DOUBLE: - return bp::object(node->getAttributeAs(key)); - case Types::STRING: - return bp::object(node->getAttributeAs(key)); - // case Types::VECTOR_BOOL: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_CHAR: - // return Wrapper::fromStdVectorToPyByteArray(node->getAttributeAs(key)); - // case Types::VECTOR_INT8: - // return Wrapper::fromStdVectorToPyByteArray(node->getAttributeAs (key)); - // case Types::VECTOR_UINT8: - // return Wrapper::fromStdVectorToPyByteArray(node->getAttributeAs(key)); - // case Types::VECTOR_INT16: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_UINT16: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_INT32: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_UINT32: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_INT64: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::VECTOR_UINT64: - // return Wrapper::fromStdVectorToPyArray(node->getAttributeAs(key)); - // case Types::HASH: - // return bp::object(node->getAttributeAs(key)); - // case Types::VECTOR_HASH: - // return - // Wrapper::fromStdVectorToPyList(node->getAttributeAs(key)); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not yet supported"); - } - - static bool hasAttribute(const Pointer& node, const std::string& key) { - return node->hasAttribute(key); - } - - static void setAttributes(const Pointer& node, const bp::object& obj) { - if (bp::extract(obj).check()) - node->setAttributes(bp::extract(obj)); - else throw KARABO_PYTHON_EXCEPTION("Python object is not of a Hash.Attributes type"); - } - - static const karabo::util::Hash::Attributes& getAttributes(const Pointer& node) { - return static_cast(node->getAttributes()); - } - - static bp::object copyAttributes(const Pointer& node) { - return bp::object(node->getAttributes()); - } - - static bp::object getType(const Pointer& node) { - return bp::object(PyTypes::from(node->getType())); - } - - static void setType(const Pointer& node, const bp::object& o_type) { - using namespace karabo::util; - if (bp::extract(o_type).check()) { - std::string type = bp::extract(o_type); - node->setType(Types::from(type)); - } else if (bp::extract(o_type).check()) { - PyTypes::ReferenceType type = bp::extract(o_type); - node->setType(PyTypes::to(type)); - } - } - }; -} // namespace karathon - -#endif /* ELEMENTWRAP_HH */ diff --git a/src/karathon/PyCoreDeviceClient.cc b/src/karathon/PyCoreDeviceClient.cc deleted file mode 100644 index a263dfdd15..0000000000 --- a/src/karathon/PyCoreDeviceClient.cc +++ /dev/null @@ -1,244 +0,0 @@ -/* - * $Id$ - * - * Author: , - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -#include "DeviceClientWrap.hh" - -using namespace karabo::xms; -using namespace karabo::util; -using namespace karabo::core; -using namespace karathon; -using namespace std; -namespace bp = boost::python; - - -void exportPyCoreDeviceClient() { - bp::class_("DeviceClientBase").def(bp::init()); - - bp::class_, bp::bases, boost::noncopyable>( - "DeviceClient") - - .def(bp::init()) - .def(bp::init&>()) - - .def("getInstanceId", &DeviceClientWrap::getInstanceIdPy) - .def("login", &DeviceClient::login) - .def("logout", &DeviceClient::logout) - .def("setInternalTimeout", (void(DeviceClient::*)(const unsigned int))(&DeviceClient::setInternalTimeout), - bp::arg("internalTimeout")) - .def("getInternalTimeout", (int(DeviceClient::*)() const)(&DeviceClient::getInternalTimeout)) - .def("exists", &DeviceClientWrap::existsPy, (bp::arg("instanceId"))) - .def("enableInstanceTracking", &DeviceClientWrap::enableInstanceTrackingPy, - "Enables tracking of new and departing device instances\n\n" - "The handlers registered with registerInstance[New|Gone|Updated]Monitor\n" - "will be called accordingly. If the handler for instanceNew is registered before\n" - "calling this method, it will be called for each device currently in the system.\n\n" - "NOTE: Use wisely!\n" - "There is a performance cost to tracking all devices since it means\n" - "subscribing to the heartbeats of all servers and devices in the system.") - .def("getSystemInformation", &DeviceClientWrap::getSystemInformationPy) - .def("getSystemTopology", &DeviceClientWrap::getSystemTopologyPy) - .def("getServers", &DeviceClientWrap::getServersPy) - .def("getClasses", &DeviceClientWrap::getClassesPy, (bp::arg("instanceId"))) - .def("getDevices", (&DeviceClientWrap::getDevicesPy)) - .def("getDevices", (&DeviceClientWrap::getDevicesByServerPy), (bp::arg("serverId"))) - .def("getDeviceSchema", - (karabo::util::Schema(DeviceClientWrap::*)(const string&))(&DeviceClientWrap::getDeviceSchema), - (bp::arg("instanceId"))) - .def("getDeviceSchemaNoWait", - (karabo::util::Schema(DeviceClientWrap::*)(const string&))(&DeviceClientWrap::getDeviceSchemaNoWait), - (bp::arg("instanceId"))) - .def("getActiveSchema", (Schema(DeviceClientWrap::*)(const string&))(&DeviceClientWrap::getActiveSchema), - (bp::arg("instanceId"))) - .def("getClassSchema", - (Schema(DeviceClientWrap::*)(const string&, const string&))(&DeviceClientWrap::getClassSchema), - (bp::arg("serverId"), bp::arg("classId"))) - .def("getProperties", &DeviceClientWrap::getPropertiesPy, (bp::arg("deviceId"))) - .def("getClassProperties", &DeviceClientWrap::getClassPropertiesPy, (bp::arg("serverId"), bp::arg("classId"))) - .def("getCurrentlySettableProperties", &DeviceClientWrap::getCurrentlySettablePropertiesPy, - (bp::arg("instanceId"))) - .def("getCurrentlyExecutableCommands", &DeviceClientWrap::getCurrentlyExecutableCommandsPy, - (bp::arg("instanceId"))) - .def("instantiate", - (bp::tuple(DeviceClientWrap::*)(const string&, const string&, const Hash&, int))( - &DeviceClientWrap::instantiatePy), - (bp::arg("serverId"), bp::arg("classId"), bp::arg("configuration"), bp::arg("timeoutInSeconds") = -1)) - .def("instantiate", - (bp::tuple(DeviceClientWrap::*)(const string&, const Hash&, int))(&DeviceClientWrap::instantiatePy), - (bp::arg("serverId"), bp::arg("configuration"), bp::arg("timeoutInSeconds") = -1)) - .def("instantiateNoWait", - (void(DeviceClient::*)(const string&, const string&, const Hash&))(&DeviceClient::instantiateNoWait), - (bp::arg("serverId"), bp::arg("classId"), bp::arg("configuration") = karabo::util::Hash())) - .def("instantiateNoWait", - (void(DeviceClient::*)(const string&, const Hash&))(&DeviceClient::instantiateNoWait), - (bp::arg("serverId"), bp::arg("configuration"))) - .def("killDevice", (bp::tuple(DeviceClientWrap::*)(const std::string&, int))(&DeviceClientWrap::killDevicePy), - (bp::arg("deviceId"), bp::arg("timeoutInSeconds") = -1)) - .def("killDeviceNoWait", (void(DeviceClient::*)(const string&))(&DeviceClient::killDeviceNoWait), - bp::arg("deviceId")) - .def("killServer", (bp::tuple(DeviceClientWrap::*)(const std::string&, int))(&DeviceClientWrap::killServerPy), - (bp::arg("serverId"), bp::arg("timeoutInSeconds") = -1)) - .def("killServerNoWait", (void(DeviceClient::*)(const string&))(&DeviceClient::killServerNoWait), - bp::arg("serverId")) - .def("get", &DeviceClientWrap::getPy, (bp::arg("instanceId"), bp::arg("key"), bp::arg("keySep") = ".")) - .def("get", &DeviceClientWrap::getConfigurationPy, (bp::arg("instanceId"))) - .def("getFromPast", &DeviceClientWrap::getPropertyHistoryPy, - (bp::arg("deviceId"), bp::arg("key"), bp::arg("from"), bp::arg("to") = "", bp::arg("maxNumData") = 0)) - .def("getPropertyHistory", &DeviceClientWrap::getPropertyHistoryPy, - (bp::arg("deviceId"), bp::arg("key"), bp::arg("from"), bp::arg("to") = "", bp::arg("maxNumData") = 0)) - .def("getConfigurationFromPast", &DeviceClientWrap::getConfigurationFromPastPy, - (bp::arg("deviceId"), bp::arg("timePoint"))) - .def("listConfigurationFromName", &DeviceClientWrap::listConfigurationFromName, - (bp::arg("deviceId"), bp::arg("namePart") = ""), - "listConfigurationFromName(deviceId, namePart): Returns the device configurations saved under names " - "that " - "contain a given name part.\n" - "If an empty name part is given, all the configurations stored for the device will be returned.\n" - "The function return is a Hash with the following keys:\n", - "\"success\" a boolean indicating whether the operation was successful.\n" - "\"reason\" a string describing the failure condition - empty on success.\n" - "\"configs\" a vector of Hashes (HashList) with each hash containing information about a saved " - "configuration.") - .def("getConfigurationFromName", &DeviceClientWrap::getConfigurationFromName, - (bp::arg("deviceId"), bp::arg("name")), - "getConfigurationFromName(deviceId, name): Returns the device configuration saved under a given name.\n" - "May return an empty result if there's no configuration stored for the device under the given name.\n" - "The function return is a Hash with the following keys:\n", - "\"success\" a boolean indicating whether the operation was successful.\n" - "\"reason\" a string describing the failure condition - empty on success.\n" - "\"config\" a hash with data about the named device configuration.") - .def("getLastConfiguration", &DeviceClientWrap::getLastConfiguration, - (bp::arg("deviceId"), bp::arg("priority") = 1), - "getLastConfiguration(deviceId, priority): Returns the most recently saved device configuration with a " - "given priority.\n" - "May return an empty result if there's no configuration stored for the device with the given priority.\n" - "The function return is a Hash with the following keys:\n", - "\"success\" a boolean indicating whether the operation was successful.\n" - "\"reason\" a string describing the failure condition - empty on success.\n" - "\"config\" a hash with data about the most recent device configuration with the given priority.") - .def("saveConfigurationFromName", &DeviceClientWrap::saveConfigurationFromNamePy, - (bp::arg("name"), bp::arg("deviceIds"), bp::arg("description") = "", bp::arg("priority") = 1, - bp::arg("user") = "."), - "saveConfigurationFromName(name, deviceIds, description, priority, user):\n" - "Saves the current device configurations (and the corresponding schemas) for a list of deviceIds\n" - "in the Configuration Database under a common name, user, priority and description.\n" - "The function return is a pair (tuple) with a boolean value indicating the operation success as\n" - "the first value and a string detailing the failure cause when the operation fails.") - .def("registerInstanceNewMonitor", &DeviceClientWrap::registerInstanceNewMonitor, bp::arg("callbackFunction"), - "registerInstanceNewMonitor(handler): Register callback handler \"handler\" to be called when new " - "instances come online\n" - "The handler function should have the signature handler(topologyEntry) where \"topologyEntry\" is a " - "Hash") - .def("registerInstanceUpdatedMonitor", &DeviceClientWrap::registerInstanceUpdatedMonitor, - bp::arg("callbackFunction"), - "registerInstanceUpdatedMonitor(handler): Register callback handler \"handler\" to be called when " - "instances update their instanceInfo\n" - "The handler function should have the signature handler(topologyEntry) where \"topologyEntry\" is a " - "Hash") - .def("registerInstanceGoneMonitor", &DeviceClientWrap::registerInstanceGoneMonitor, - bp::arg("callbackFunction"), - "registerInstanceGoneMonitor(handler): Register callback handler \"handler\" to be called when " - "instances " - "go offline\n" - "The handler function should have the signature handler(instanceId, instanceInfo) where:\n" - "\"instanceId\" is a string containing name of the device which went offline\n" - "\"instanceInfo\" is a Hash") - .def("registerSchemaUpdatedMonitor", &DeviceClientWrap::registerSchemaUpdatedMonitor, - bp::arg("callbackFunction"), - "registerSchemaUpdatedMonitor(handler): Register a callback handler \"handler\" to be triggered if an " - "instance receives a schema update from the distributed system\n" - "The handler function should have the signature handler(instanceId, schema) where:\n" - "\"instanceId\" is a string containing name of the device which updated schema\n" - "\"schema\" is the updated schema\n\n" - "Note: Currently, registering only a schema update monitor with an instance\n" - "of a DeviceClient is not enough to have the registered call-back activated.\n" - "A workaround for this is to also register a property monitor with the\n" - "same instance of DeviceClient that has been used to register the schema\n" - "update monitor.\n\n") - .def("registerPropertyMonitor", - (bool(DeviceClientWrap::*)(const string&, const string&, const bp::object&, const bp::object&))( - &DeviceClientWrap::registerPropertyMonitor), - (bp::arg("instanceId"), bp::arg("key"), bp::arg("callbackFunction"), bp::arg("userData") = bp::object())) - .def("registerDeviceMonitor", - (void(DeviceClientWrap::*)(const string&, const bp::object&, const bp::object&))( - &DeviceClientWrap::registerDeviceMonitor), - (bp::arg("instanceId"), bp::arg("callbackFunction"), bp::arg("userData") = bp::object())) - .def("setDeviceMonitorInterval", &DeviceClientWrap::setDeviceMonitorIntervalPy, bp::arg("milliseconds")) - .def("unregisterPropertyMonitor", - (void(DeviceClient::*)(const string&, const string&))(&DeviceClient::unregisterPropertyMonitor), - (bp::arg("instanceId"), bp::arg("key"))) - .def("unregisterDeviceMonitor", - (void(DeviceClient::*)(const string&))(&DeviceClient::unregisterDeviceMonitor), bp::arg("instanceId")) - .def("registerChannelMonitor", &DeviceClientWrap::registerChannelMonitorPy, - (bp::arg("channelName"), bp::arg("dataHandler") = bp::object(), - bp::arg("inputChannelCfg") = karabo::util::Hash(), bp::arg("eosHandler") = bp::object(), - bp::arg("inputHandler") = bp::object(), bp::arg("statusTracker") = bp::object()), - "Register a handler to monitor defined output channel.\n\n" - "Internally, an InputChannel is created and configured.\n" - "@param channelName identifies the channel as a concatenation of the id of\n" - " its device, a colon (:) and the name of the output\n" - " channel (e.g. A/COOL/DEVICE:output)\n" - "@param dataHandler called when data arrives, arguments are data (Hash) and\n" - " meta data (Hash/MetaData)\n" - "@param inputChannelCfg configures the channel via InputChannel.create(..)\n" - " use default except you know what your are doing\n" - " for experts: \"connectedOutputChannels\" will be overwritten\n" - "@param eosHandler called on end of stream, argument is the InputChannel\n\n" - "@param inputHandler called when data arrives, argument is the InputChannel\n\n" - "@param statusTracker called with a 'ConnectionStatus' as argument when the connection\n" - " status of the underlying InputChannel changes\n" - "@return False if channel is already registered") - .def("unregisterChannelMonitor", &DeviceClientWrap::unregisterChannelMonitorPy, bp::arg("channelName"), - "Unregister monitoring of output channel\n\n" - "@param channelName identifies the channel as a concatenation of the id of\n" - " its devices, a colon (:) and the name of the output\n" - " channel (e.g. A/COOL/DEVICE:output)\n\n" - "@return False if channel was not registered") - .def("set", - (void(DeviceClientWrap::*)(const string&, const string&, const bp::object&, const std::string&, int))( - &DeviceClientWrap::setPy), - (bp::arg("deviceId"), bp::arg("key"), bp::arg("value"), bp::arg("keySep") = ".", - bp::arg("timeoutInSeconds") = -1)) - .def("set", - (void(DeviceClientWrap::*)(const string&, const karabo::util::Hash&, int))(&DeviceClientWrap::setPy), - (bp::arg("deviceId"), bp::arg("hash"), bp::arg("timeoutInSeconds") = -1)) - .def("setAttribute", - (void(DeviceClientWrap::*)(const std::string&, const std::string&, const std::string&, const bp::object&, - int))(&DeviceClientWrap::setAttributePy), - (bp::arg("deviceId"), bp::arg("key"), bp::arg("attributeKey"), bp::arg("attributeValue"), - bp::arg("timeoutInSeconds") = -1)) - .def("setNoWait", &DeviceClientWrap::setNoWaitPy, - (bp::arg("instanceId"), bp::arg("key"), bp::arg("value"), bp::arg("keySep") = ".")) - .def("execute", &DeviceClientWrap::executePy, - (bp::arg("instanceId"), bp::arg("functionName"), bp::arg("timeoutInSeconds") = -1)) - .def("executeNoWait", &DeviceClientWrap::executeNoWaitPy, (bp::arg("instanceId"), bp::arg("functionName"))) - .def("getOutputChannelSchema", &DeviceClientWrap::getOutputChannelSchema, - (bp::arg("deviceId"), bp::arg("outputChannelName"))) - .def("getOutputChannelNames", &DeviceClientWrap::getOutputChannelNames, (bp::arg("deviceId"))) - .def("getDataSourceSchemaAsHash", &DeviceClientWrap::getDataSourceSchemaAsHashPy, - (bp::arg("dataSourceId"), - bp::arg("accessType") = AccessType::INIT | AccessType::READ | AccessType::WRITE)) - .def("lock", &DeviceClientWrap::lockPy, - (bp::arg("deviceId"), bp::arg("recursive") = false, bp::arg("timeout") = -1)); -} diff --git a/src/karathon/PyCoreLockWrap.cc b/src/karathon/PyCoreLockWrap.cc deleted file mode 100644 index be1d4bd66c..0000000000 --- a/src/karathon/PyCoreLockWrap.cc +++ /dev/null @@ -1,55 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: LockWrap.cc - * Author: haufs - * - * Created on October 13, 2016, 1:12 PM - */ -#include "PyCoreLockWrap.hh" - -#include "boost/python.hpp" - - -using namespace karabo::core; -namespace bp = boost::python; - - -namespace karathon { - void LockWrap::lock(bool recursive) { - m_lock->lock(recursive); - } - - - void LockWrap::unlock() { - m_lock->unlock(); - } - - - bool LockWrap::valid() { - return m_lock->valid(); - } -} // namespace karathon - - -void exportPyCoreLock() { - bp::class_ >("Lock", bp::no_init) - .def("lock", &karathon::LockWrap::lock, bp::arg("recursive") = false) - .def("unlock", &karathon::LockWrap::unlock) - .def("valid", &karathon::LockWrap::valid); -} diff --git a/src/karathon/PyCoreLockWrap.hh b/src/karathon/PyCoreLockWrap.hh deleted file mode 100644 index 46d4f702c9..0000000000 --- a/src/karathon/PyCoreLockWrap.hh +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: PyCoreLockWrap.hh - * Author: haufs - * - * Created on October 13, 2016, 6:18 PM - */ - -#ifndef KARATHON_PYCORELOCKWRAP_HH -#define KARATHON_PYCORELOCKWRAP_HH - -#include - - -namespace karathon { - - class LockWrap { - boost::shared_ptr m_lock; - - public: - LockWrap(const boost::shared_ptr& l) : m_lock(l){}; - - - /** - * Reacquire a lock if this lock was previously unlocked - * @param recursive: allow recursive locking if true - */ - void lock(bool recursive = false); - - /** - * Unlock this lock - */ - void unlock(); - - /** - * Returns if this lock is currently valid. Note that the locked - * device will be queried through the distributed system when - * asking for lock validity. - */ - bool valid(); - }; -} // namespace karathon -#endif /* KARATHON_PYCORELOCKWRAP_HH */ diff --git a/src/karathon/PyIoFileTools.cc b/src/karathon/PyIoFileTools.cc deleted file mode 100644 index c2659ef6a5..0000000000 --- a/src/karathon/PyIoFileTools.cc +++ /dev/null @@ -1,403 +0,0 @@ -/* - * $Id$ - * - * Author: - * Modified (2 May 2013): - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "PythonFactoryMacros.hh" -#include "PythonMacros.hh" -#include "ScopedGILAcquire.hh" -#include "ScopedGILRelease.hh" -#include "Wrapper.hh" - -using namespace karabo::util; -using namespace karabo::io; -using namespace std; -namespace bp = boost::python; - -namespace karathon { - - - struct AbstractInputWrap { - static void reconfigure(AbstractInput::Pointer self, const karabo::util::Hash& configuration) { - self->reconfigure(configuration); - } - - - static bp::object getInstanceId(AbstractInput::Pointer self) { - return bp::object(self->getInstanceId()); - } - - - static void setInstanceId(AbstractInput::Pointer self, const std::string& instanceId) { - self->setInstanceId(instanceId); - } - - - static void setInputHandlerType(AbstractInput::Pointer self, const std::string& language, - const std::string& inputType) { - self->setInputHandlerType(language, inputType); - } - - - static bool needsDeviceConnection(AbstractInput::Pointer self) { - return self->needsDeviceConnection(); - } - - - static bp::object getConnectedOutputChannels(AbstractInput::Pointer self) { - return Wrapper::fromStdVectorToPyHashList(self->getConnectedOutputChannels()); - } - - - static void connectNow(AbstractInput::Pointer self, const karabo::util::Hash& config) { - ScopedGILRelease nogil; - self->connect(config); - } - - - static bool canCompute(AbstractInput::Pointer self) { - return self->canCompute(); - } - - - static void update(AbstractInput::Pointer self) { - ScopedGILRelease nogil; - self->update(); - } - - - static void registerIOEventHandler(AbstractInput::Pointer self, const bp::object& handler) { - self->registerIOEventHandler(handler); - } - - - static void registerEndOfStreamEventHandler(AbstractInput::Pointer self, const bp::object& handler) { - self->registerEndOfStreamEventHandler(handler); - } - }; - - - template - struct OutputWrap { - static void update(const boost::shared_ptr >& self) { - ScopedGILRelease nogil; - self->update(); - } - }; - - - template - struct InputWrap { - static void registerIOEventHandler(const boost::shared_ptr >& self, - const bp::object& handler) { - self->registerIOEventHandler(handler); - } - - - static void registerEndOfStreamEventHandler(const boost::shared_ptr >& self, - const bp::object& handler) { - self->registerEndOfStreamEventHandler(handler); - } - }; - - - template - struct loadFromFileWrap { - static bp::object loadWrap(const bp::object& fileNameObj, const bp::object& conf) { - if (PyUnicode_Check(fileNameObj.ptr())) { - string fileName = bp::extract(fileNameObj); - Hash config = bp::extract(conf); - T t = T(); - { - ScopedGILRelease nogil; - karabo::io::loadFromFile(t, fileName, config); - } - return bp::object(t); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python first argument in 'loadFromFile' must be a string, second optional argument is a Hash"); - } - } - }; - - - template - struct TextSerializerWrap { - static bp::object save(karabo::io::TextSerializer& s, const T& object) { - std::string archive; - s.save(object, archive); - return bp::object(archive); - } - - - static bp::object load(karabo::io::TextSerializer& s, const bp::object& obj) { - if (PyBytes_Check(obj.ptr())) { - PyObject* bytes = obj.ptr(); - size_t size = PyBytes_Size(bytes); - char* data = PyBytes_AsString(bytes); - T object; - s.load(object, data, size); - return bp::object(object); - } else if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - T object; - s.load(object, data, size); - return bp::object(object); - } else if (bp::extract(obj).check()) { - T object; - s.load(object, bp::extract(obj)); - return bp::object(object); - } - throw KARABO_PYTHON_EXCEPTION("Python object must be either of type bytes, bytearray or string"); - } - }; -} // namespace karathon - - -void exportPyIo() { - { - bp::class_, boost::noncopyable>("AbstractInput", bp::init<>()) - .def("reconfigure", &karathon::AbstractInputWrap::reconfigure, (bp::arg("input"))) - .def("setInstanceId", &karathon::AbstractInputWrap::setInstanceId, (bp::arg("instanceId"))) - .def("getInstanceId", &karathon::AbstractInputWrap::getInstanceId) - .def("setInputHandlerType", &karathon::AbstractInputWrap::setInputHandlerType, (bp::arg("type"))) - .def("needsDeviceConnection", &karathon::AbstractInputWrap::needsDeviceConnection) - .def("getConnectedOutputChannels", &karathon::AbstractInputWrap::getConnectedOutputChannels) - .def("connectNow", &karathon::AbstractInputWrap::connectNow, (bp::arg("outputChannelInfo"))) - .def("canCompute", &karathon::AbstractInputWrap::canCompute) - .def("update", &karathon::AbstractInputWrap::update) - .def("registerIOEventHandler", &karathon::AbstractInputWrap::registerIOEventHandler, (bp::arg("handler"))) - .def("registerEndOfStreamEventHandler", &karathon::AbstractInputWrap::registerEndOfStreamEventHandler, - (bp::arg("handler"))) KARABO_PYTHON_FACTORY_CONFIGURATOR(AbstractInput); - } -} - -// TODO: DEPRECATE THIS - - -void exportPyIoFileTools() { - bp::def("saveToFile", (void (*)(Schema const&, string const&, Hash const&))(&karabo::io::saveToFile), - (bp::arg("object"), bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); - - bp::def("saveToFile", (void (*)(Hash const&, string const&, Hash const&))(&karabo::io::saveToFile), - (bp::arg("object"), bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); - - bp::def("loadFromFile", &karathon::loadFromFileWrap::loadWrap, - (bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); - - bp::def("loadFromFile", (void (*)(Hash&, string const&, Hash const&))(&karabo::io::loadFromFile), - (bp::arg("object"), bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); - - bp::def("loadFromFile", (void (*)(Schema&, string const&, Hash const&))(&karabo::io::loadFromFile), - (bp::arg("object"), bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); -} - - -template -void exportPyIOFileTools1() { - string className = T::classInfo().getClassName(); - - bp::def(string("save" + className + "ToFile").c_str(), - (void (*)(T const&, string const&, Hash const&))(&karabo::io::saveToFile), - (bp::arg("object"), bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); - - bp::def(string("load" + className + "FromFile").c_str(), &karathon::loadFromFileWrap::loadWrap, - (bp::arg("filename"), bp::arg("config") = karabo::util::Hash())); -} - - -template -void exportPyIoOutput() { - { // exposing karabo::io::Output - typedef karabo::io::Output SpecificOutput; - bp::class_, boost::noncopyable>( - string("Output" + T::classInfo().getClassName()).c_str(), bp::no_init) - .def("write", (void(SpecificOutput::*)(T const&))(&SpecificOutput::write), (bp::arg("data"))) - .def("use_count", &boost::shared_ptr::use_count) - .def("update", &karathon::OutputWrap::update) KARABO_PYTHON_FACTORY_CONFIGURATOR(SpecificOutput); - } -} - - -template -void exportPyIoInput() { - { // exposing karabo::io::Input - typedef karabo::io::Input SpecificInput; - bp::class_, boost::noncopyable>( - string("Input" + T::classInfo().getClassName()).c_str(), bp::no_init) - .def("read", (void(SpecificInput::*)(T&, size_t))(&SpecificInput::read), - (bp::arg("data"), bp::arg("idx") = 0)) - .def("size", (size_t(SpecificInput::*)() const)(&SpecificInput::size)) - .def("update", (void(SpecificInput::*)())(&SpecificInput::update)) - .def("registerReadHandler", &karathon::InputWrap::registerIOEventHandler) - .def("registerEndOfStreamHandler", &karathon::InputWrap::registerEndOfStreamEventHandler) - .def("use_count", &boost::shared_ptr::use_count) - - KARABO_PYTHON_FACTORY_CONFIGURATOR(SpecificInput); - } -} - - -template -void exportPyIoTextSerializer() { - { // exposing karabo::io::TextSerializer, where T : karabo::util::Hash or karabo::util::Schema - typedef karabo::io::TextSerializer SpecificSerializer; - bp::class_( - string("TextSerializer" + T::classInfo().getClassName()).c_str(), bp::no_init) - .def("save", &karathon::TextSerializerWrap().save, (bp::arg("object")), - "Saves an object as a string.\nExample:\n\t" - "h = Hash('a.b.c',1,'x.y.z',[1,2,3,4,5,6,7])\n\tser = TextSerializerHash()\n\tarchive = " - "ser.save(h)\n\tassert archive.__class__.__name__ == 'str'") - .def("load", &karathon::TextSerializerWrap().load, (bp::arg("archive")), - "Loads \"bytearray\" or \"str\" archive and returns a new object.\nExample:\n\th = " - "Hash('a.b.c',1,'x.y.z',[1,2,3,4,5,6,7])\n\tser = TextSerializerHash()\n\t" - "archive = ser.save(h)\n\th2 = ser.load(archive)\n\tassert similar(h, h2)") - KARABO_PYTHON_FACTORY_CONFIGURATOR(SpecificSerializer); - bp::register_ptr_to_python >(); - } -} - - -template -class BinarySerializerWrap { - public: - static bp::object save(karabo::io::BinarySerializer& s, const T& object) { - std::vector v; - s.save(object, v); - return bp::object(bp::handle<>(PyBytes_FromStringAndSize(&v[0], v.size()))); - } - - - static bp::object load(karabo::io::BinarySerializer& s, const bp::object& obj) { - if (PyBytes_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyBytes_Size(bytearray); - char* data = PyBytes_AsString(bytearray); - T object; - s.load(object, data, size); - return bp::object(object); - // TODO: Check whether there is a better way to go from python string to vector or the like... - } else if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - T object; - s.load(object, data, size); - return bp::object(object); - // TODO: Check whether there is a better way to go from python string to vector or the like... - } else if (bp::extract(obj).check()) { - T object; - const string& tmp = bp::extract(obj); - s.load(object, tmp.c_str(), tmp.size() - 1); - return bp::object(object); - } - throw KARABO_PYTHON_EXCEPTION("Python object type must be either string, bytes or bytearray!"); - } -}; - - -template <> -class BinarySerializerWrap { - public: - static bp::object save(karabo::io::BinarySerializer& s, const boost::shared_ptr& object) { - std::vector v; - s.save(object, v); - return bp::object(bp::handle<>(PyBytes_FromStringAndSize(&v[0], v.size()))); - } - - - static bp::object load(karabo::io::BinarySerializer& s, const bp::object& obj) { - if (PyBytes_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyBytes_Size(bytearray); - char* data = PyBytes_AsString(bytearray); - Hash::Pointer object(new Hash); - s.load(object, data, size); - return bp::object(object); - // TODO: Check whether there is a better way to go from python string to vector or the like... - } else if (PyByteArray_Check(obj.ptr())) { - PyObject* bytearray = obj.ptr(); - size_t size = PyByteArray_Size(bytearray); - char* data = PyByteArray_AsString(bytearray); - Hash::Pointer object(new Hash); - s.load(object, data, size); - return bp::object(object); - // TODO: Check whether there is a better way to go from python string to vector or the like... - } else if (bp::extract(obj).check()) { - Hash::Pointer object(new Hash); - const string& tmp = bp::extract(obj); - s.load(object, tmp.c_str(), tmp.size() - 1); - return bp::object(object); - } - throw KARABO_PYTHON_EXCEPTION("Python object type must be either string, bytes or bytearray!"); - } -}; - - -template -void exportPyIoBinarySerializer() { - bp::docstring_options docs(true, true, false); - typedef karabo::io::BinarySerializer SpecificSerializer; - bp::class_( - string("BinarySerializer" + T::classInfo().getClassName()).c_str(), bp::no_init) - .def("save", &BinarySerializerWrap().save, (bp::arg("object")), - "Saves an object as a bytearray.\nExample:\n\t" - "h = Hash('a.b.c',1,'x.y.z',[1,2,3,4,5,6,7])\n\tser = BinarySerializerHash()\n\tarchive = " - "ser.save(h)\n\tassert archive.__class__.__name__ == 'bytearray'") - - .def("load", &BinarySerializerWrap().load, (bp::arg("archive")), - "Loads \"bytearray\" archive and returns new object.\nExample:\n\th = " - "Hash('a.b.c',1,'x.y.z',[1,2,3,4,5,6,7])\n\tser = BinarySerializerHash()\n\t" - "archive = ser.save(h)\n\th2 = ser.load(archive)\n\tassert similar(h, h2)") - KARABO_PYTHON_FACTORY_CONFIGURATOR(SpecificSerializer); - bp::register_ptr_to_python >(); -} - - -// **** EXPLICIT TEMPLATE INSTANTIATIONS **** - -template void exportPyIOFileTools1(); -template void exportPyIOFileTools1(); - -template void exportPyIoOutput(); -template void exportPyIoOutput(); - -template void exportPyIoInput(); -template void exportPyIoInput(); - -template void exportPyIoBinarySerializer(); -template void exportPyIoBinarySerializer(); - -template void exportPyIoTextSerializer(); -template void exportPyIoTextSerializer(); diff --git a/src/karathon/PyLogLogger.cc b/src/karathon/PyLogLogger.cc deleted file mode 100644 index 5322f84d38..0000000000 --- a/src/karathon/PyLogLogger.cc +++ /dev/null @@ -1,160 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include - -#include "PythonFactoryMacros.hh" -#include "boost/python.hpp" - -namespace bp = boost::python; -using namespace karabo::log; -using namespace karabo::util; -using namespace krb_log4cpp; -using namespace std; - - -namespace karathon { - - struct PriorityWrap { - static bp::object getPriorityNamePy(int priority) { - return bp::object(krb_log4cpp::Priority::getPriorityName(priority)); - } - }; - - struct LoggerWrap { - static void logDebug(const std::string& message, const std::string& category) { - karabo::log::Logger::logDebug(category) << message; - } - - static void logInfo(const std::string& message, const std::string& category) { - karabo::log::Logger::logInfo(category) << message; - } - - static void logWarn(const std::string& message, const std::string& category) { - karabo::log::Logger::logWarn(category) << message; - } - - static void logError(const std::string& message, const std::string& category) { - karabo::log::Logger::logError(category) << message; - } - }; - -} // namespace karathon - - -void exportPyLogLogger() { - { - bp::enum_("PriorityLevel", "This enumeration describes priority levels") - .value("EMERG", krb_log4cpp::Priority::EMERG) - .value("FATAL", krb_log4cpp::Priority::FATAL) - .value("ALERT", krb_log4cpp::Priority::ALERT) - .value("CRIT", krb_log4cpp::Priority::CRIT) - .value("ERROR", krb_log4cpp::Priority::ERROR) - .value("WARN", krb_log4cpp::Priority::WARN) - .value("NOTICE", krb_log4cpp::Priority::NOTICE) - .value("INFO", krb_log4cpp::Priority::INFO) - .value("DEBUG", krb_log4cpp::Priority::DEBUG) - .value("NOTSET", krb_log4cpp::Priority::NOTSET); - - bp::class_ p("Priority", bp::init<>()); - - p.def("getPriorityName", &karathon::PriorityWrap::getPriorityNamePy, (bp::arg("priority"))) - .staticmethod("getPriorityName"); - - p.def("getPriorityValue", (int (*)(string const&))(&krb_log4cpp::Priority::getPriorityValue), - (bp::arg("priorityName"))) - .staticmethod("getPriorityValue"); - } - - { // krb_log4cpp::Category - bp::class_ ct("Category", bp::no_init); - - ct.def("getInstance", (krb_log4cpp::Category & (*)(string const&))(&krb_log4cpp::Category::getInstance), - bp::arg("name"), bp::return_internal_reference<>()) - .staticmethod("getInstance"); - - ct.def("getName", (string const& (krb_log4cpp::Category::*)() const)(&krb_log4cpp::Category::getName), - bp::return_value_policy()); - - ct.def("getAdditivity", (bool(krb_log4cpp::Category::*)() const)(&krb_log4cpp::Category::getAdditivity)); - - ct.def("getPriority", (int(krb_log4cpp::Category::*)() const)(&krb_log4cpp::Category::getPriority)); - - ct.def("getRootPriority", (int (*)())(&krb_log4cpp::Category::getRootPriority)).staticmethod("getRootPriority"); - - ct.def("getChainedPriority", - (int(krb_log4cpp::Category::*)() const)(&krb_log4cpp::Category::getChainedPriority)); - - ct.def("setPriority", (void(krb_log4cpp::Category::*)(int))(&krb_log4cpp::Category::setPriority), - bp::arg("newprio")); - - ct.def("setRootPriority", (void (*)(int))(&krb_log4cpp::Category::setRootPriority), bp::arg("newprio")) - .staticmethod("setRootPriority"); - - ct.def("WARN", (void(krb_log4cpp::Category::*)(string const&))(&krb_log4cpp::Category::warn), - bp::arg("message")); - - ct.def("DEBUG", (void(krb_log4cpp::Category::*)(string const&))(&krb_log4cpp::Category::debug), - bp::arg("message")); - - ct.def("INFO", (void(krb_log4cpp::Category::*)(string const&))(&krb_log4cpp::Category::info), - bp::arg("message")); - - ct.def("ERROR", (void(krb_log4cpp::Category::*)(string const&))(&krb_log4cpp::Category::error), - bp::arg("message")); - } - - { // karabo::log::Logger - bp::class_("Logger", bp::no_init) - .def("expectedParameters", &Logger::expectedParameters, (bp::arg("schema"))) - .staticmethod("expectedParameters") - .def("configure", &Logger::configure, (bp::arg("config") = Hash())) - .staticmethod("configure") - .def("useOstream", &Logger::useOstream, (bp::arg("category") = "", bp::arg("inheritAppenders") = true)) - .staticmethod("useOstream") - .def("useFile", &Logger::useFile, (bp::arg("category") = "", bp::arg("inheritAppenders") = true)) - .staticmethod("useFile") - .def("useCache", &Logger::useCache, (bp::arg("category") = "", bp::arg("inheritAppenders") = true)) - .staticmethod("useCache") - .def("getCachedContent", &Logger::getCachedContent, (bp::arg("nMessages") = 100u)) - .staticmethod("getCachedContent") - .def("reset", &Logger::reset) - .staticmethod("reset") - .def("logDebug", &karathon::LoggerWrap::logDebug, (bp::arg("message"), bp::arg("category") = "")) - .staticmethod("logDebug") - .def("logInfo", &karathon::LoggerWrap::logInfo, (bp::arg("message"), bp::arg("category") = "")) - .staticmethod("logInfo") - .def("logWarn", &karathon::LoggerWrap::logWarn, (bp::arg("message"), bp::arg("category") = "")) - .staticmethod("logWarn") - .def("logError", &karathon::LoggerWrap::logError, (bp::arg("message"), bp::arg("category") = "")) - .staticmethod("logError") - .def("setPriority", &Logger::setPriority, (bp::arg("priority"), bp::arg("category") = "")) - .staticmethod("setPriority") - .def("getPriority", &Logger::getPriority, (bp::arg("category") = ""), - bp::return_value_policy()) - .staticmethod("getPriority") - .def("getCategory", (krb_log4cpp::Category & (*)(const string&))(&Logger::getCategory), - (bp::arg("logCategorie") = ""), bp::return_internal_reference<>()) - .staticmethod("getCategory") KARABO_PYTHON_FACTORY_CONFIGURATOR(Logger); - bp::register_ptr_to_python >(); - } -} diff --git a/src/karathon/PyUtilAlarmElement.cc b/src/karathon/PyUtilAlarmElement.cc deleted file mode 100644 index f79ed8a723..0000000000 --- a/src/karathon/PyUtilAlarmElement.cc +++ /dev/null @@ -1,74 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -#include "PythonMacros.hh" -#include "boost/python.hpp" -#include "boost/python/raw_function.hpp" - - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -class AlarmConditionElementWrap { - public: - static AlarmConditionElement& initialValuePy(AlarmConditionElement& self, const bp::object& value) { - const std::string className = bp::extract(value.attr("__class__").attr("__name__")); - if (className == "AlarmCondition") { - const std::string condition = bp::extract(value.attr("asString")()); - return self.initialValue(karabo::util::AlarmCondition::fromString(condition)); - } else { - throw KARABO_PYTHON_EXCEPTION("initialValue() expects parameter of type AlarmCondition."); - } - } -}; - - -void exportPyUtilAlarmConditionElement() { - bp::implicitly_convertible(); - bp::class_("ALARM_ELEMENT", bp::init((bp::arg("expected")))) - .def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()) - .def("commit", &AlarmConditionElement::commit, bp::return_internal_reference<>()) - .def("commit", - (AlarmConditionElement & - (AlarmConditionElement::*)(karabo::util::Schema&))(&AlarmConditionElement::commit), - bp::arg("expected"), bp::return_internal_reference<>()) - .def("description", &AlarmConditionElement::description, bp::return_internal_reference<>()) - .def("displayedName", &AlarmConditionElement::displayedName, bp::return_internal_reference<>()) - .def("key", &AlarmConditionElement::key, bp::return_internal_reference<>()) - .def("tags", - (AlarmConditionElement & - (AlarmConditionElement::*)(std::string const&, std::string const&))(&AlarmConditionElement::tags), - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) - .def("tags", - (AlarmConditionElement & - (AlarmConditionElement::*)(std::vector const&))(&AlarmConditionElement::tags), - (bp::arg("tags")), bp::return_internal_reference<>()) - .def("defaultValue", &AlarmConditionElementWrap::initialValuePy, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("initialValue", &AlarmConditionElementWrap::initialValuePy, (bp::arg("value")), - bp::return_internal_reference<>()); -} diff --git a/src/karathon/PyUtilClassInfo.cc b/src/karathon/PyUtilClassInfo.cc deleted file mode 100644 index 34504041b2..0000000000 --- a/src/karathon/PyUtilClassInfo.cc +++ /dev/null @@ -1,44 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -using namespace karabo::util; -using namespace std; -namespace bp = boost::python; - - -void exportPyUtilClassInfo() { // exposing karabo::util::ClassInfo - bp::class_("ClassInfo", bp::init( - (bp::arg("classId"), bp::arg("signature"), bp::arg("classVersion")))) - .def("getClassId", (string const& (ClassInfo::*)() const)(&ClassInfo::getClassId), - bp::return_value_policy()) - .def("getClassName", (string const& (ClassInfo::*)() const)(&ClassInfo::getClassName), - bp::return_value_policy()) - .def("getVersion", (string const& (ClassInfo::*)() const)(&ClassInfo::getVersion), - bp::return_value_policy()) - .def("getLogCategory", (string const& (ClassInfo::*)() const)(&ClassInfo::getLogCategory), - bp::return_value_policy()) - .def("getNamespace", (string const& (ClassInfo::*)() const)(&ClassInfo::getNamespace), - bp::return_value_policy()); -} diff --git a/src/karathon/PyUtilDateTimeString.cc b/src/karathon/PyUtilDateTimeString.cc deleted file mode 100644 index 1e59914560..0000000000 --- a/src/karathon/PyUtilDateTimeString.cc +++ /dev/null @@ -1,69 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include -#include - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -void exportPyUtilDateTimeString() { - bp::class_ dts("DateTimeString", bp::init<>()); - - dts.def(bp::init((bp::arg("timePoint")))); - - dts.def(bp::init( - (bp::arg("inputDateStr"), bp::arg("inputTimeStr"), bp::arg("inputFractionSecondStr"), - bp::arg("inputTimeZoneStr")))); - - bp::implicitly_convertible(); - - dts.def("getDate", (const std::string& (DateTimeString::*)() const)(&DateTimeString::getDate), - bp::return_value_policy()); - - dts.def("getTime", (const std::string& (DateTimeString::*)() const)(&DateTimeString::getTime), - bp::return_value_policy()); - - dts.def("getFractionalSeconds", - (const std::string (DateTimeString::*)() const)(&DateTimeString::getFractionalSeconds)); - - dts.def("getFractionalSeconds", - (const unsigned long long (DateTimeString::*)() const)(&DateTimeString::getFractionalSeconds)); - - dts.def("getTimeZone", (const std::string& (DateTimeString::*)() const)(&DateTimeString::getTimeZone), - bp::return_value_policy()); - - dts.def("getDateTime", (const std::string& (DateTimeString::*)() const)(&DateTimeString::getDateTime), - bp::return_value_policy()); - - dts.def("isStringValidIso8601", (const bool (*)(string const&))(&DateTimeString::isStringValidIso8601), - (bp::arg("timePoint"))); - dts.staticmethod("isStringValidIso8601"); - - dts.def("isStringKaraboValidIso8601", (const bool (*)(string const&))(&DateTimeString::isStringKaraboValidIso8601), - (bp::arg("timePoint"))); - dts.staticmethod("isStringKaraboValidIso8601"); - - dts.def("getSecondsSinceEpoch", - (const unsigned long long (DateTimeString::*)())(&DateTimeString::getSecondsSinceEpoch)); -} diff --git a/src/karathon/PyUtilDims.cc b/src/karathon/PyUtilDims.cc deleted file mode 100644 index 9d555d68c1..0000000000 --- a/src/karathon/PyUtilDims.cc +++ /dev/null @@ -1,58 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -#include "DimsWrap.hh" - - -namespace bp = boost::python; -using namespace karabo::util; -using namespace karathon; -using namespace std; - - -void exportPyUtilDims() { - { bp::class_ d("_DimsIntern", bp::no_init); } - - { - bp::class_ > d("Dims"); - - d.def(bp::init()); - d.def(bp::init()); - d.def(bp::init()); - d.def(bp::init()); - d.def(bp::init()); - d.def("rank", (size_t(DimsWrap::*)())(&DimsWrap::rank), ""); - d.def("size", (unsigned long long (DimsWrap::*)())(&DimsWrap::size)); - d.def("extentIn", (unsigned long long (DimsWrap::*)(size_t))(&DimsWrap::extentIn)); - - d.def("toList", &DimsWrap::toVectorPy); - d.def("toArray", &DimsWrap::toArrayPy); - } - - { - bp::def("setDims", (void (*)(Hash&, const std::string&, const Dims&, const char))(&karabo::util::setDims), - (bp::arg("hash"), bp::arg("path"), bp::arg("dims"), bp::arg("sep") = '.')); - } -} diff --git a/src/karathon/PyUtilEpochstamp.cc b/src/karathon/PyUtilEpochstamp.cc deleted file mode 100644 index c71a2d2cc5..0000000000 --- a/src/karathon/PyUtilEpochstamp.cc +++ /dev/null @@ -1,132 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include -#include -#include - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -void exportPyUtilEpochstamp() { - bp::enum_("TIME_UNITS") - .value("ATTOSEC", karabo::util::ATTOSEC) - .value("FEMTOSEC", karabo::util::FEMTOSEC) - .value("PICOSEC", karabo::util::PICOSEC) - .value("NANOSEC", karabo::util::NANOSEC) - .value("MICROSEC", karabo::util::MICROSEC) - .value("MILLISEC", karabo::util::MILLISEC) - .value("ONESECOND", karabo::util::ONESECOND) - .value("SECOND", karabo::util::SECOND) - .value("MINUTE", karabo::util::MINUTE) - .value("HOUR", karabo::util::HOUR) - .value("DAY", karabo::util::DAY) - .export_values(); - - bp::class_ e("Epochstamp", bp::init<>()); - e.def(bp::init((bp::arg("seconds"), bp::arg("fractions")))); - e.def(bp::init((bp::arg("tm")))); - bp::implicitly_convertible(); - - e.def(bp::init((bp::arg("tv")))); - bp::implicitly_convertible(); - - e.def(bp::init((bp::arg("ts")))); - bp::implicitly_convertible(); - - e.def(bp::init((bp::arg("pTimeStr")))); - bp::implicitly_convertible(); - - e.def("getSeconds", (unsigned long long const& (Epochstamp::*)() const)(&Epochstamp::getSeconds), - bp::return_value_policy()); - - e.def("getFractionalSeconds", - (unsigned long long const& (Epochstamp::*)() const)(&Epochstamp::getFractionalSeconds), - bp::return_value_policy()); - - e.def("getTime", (time_t(Epochstamp::*)() const)(&Epochstamp::getTime)); - - e.def("getTimeOfDay", (timeval(Epochstamp::*)() const)(&Epochstamp::getTimeOfDay)); - - e.def("getClockTime", (timespec(Epochstamp::*)() const)(&Epochstamp::getClockTime)); - - typedef void (::karabo::util::Epochstamp::*now_function_type)(); - - e.def("now", (void(Epochstamp::*)())(&Epochstamp::now)); - - e.def("elapsed", (TimeDuration(Epochstamp::*)(Epochstamp const&) const)(&Epochstamp::elapsed), - (bp::arg("other") = karabo::util::Epochstamp())); - - e.def("fromHashAttributes", &Epochstamp::fromHashAttributes, bp::arg("attributes")); - e.staticmethod("fromHashAttributes"); - - e.def("toHashAttributes", &Epochstamp::toHashAttributes, bp::arg("attributes")); - - e.def("hashAttributesContainTimeInformation", &Epochstamp::hashAttributesContainTimeInformation, - bp::arg("attributes")); - e.staticmethod("hashAttributesContainTimeInformation"); - - e.def("toIso8601", (string(Epochstamp::*)(karabo::util::TIME_UNITS, bool) const)(&Epochstamp::toIso8601), - (bp::arg("precision") = karabo::util::MICROSEC, bp::arg("extended") = (bool)(false))); - - e.def("toIso8601Ext", (string(Epochstamp::*)(karabo::util::TIME_UNITS, bool) const)(&Epochstamp::toIso8601Ext), - (bp::arg("precision") = karabo::util::MICROSEC, bp::arg("extended") = (bool)(false))); - - e.def("toTimestamp", (double(Epochstamp::*)() const)(&Epochstamp::toTimestamp)); - - e.def("toFormattedString", - (string(Epochstamp::*)(const string&, const string&) const)(&Epochstamp::toFormattedString), - (bp::arg("format") = "%Y-%b-%d %H:%M:%S", bp::arg("localTimeZone") = "Z")); - - e.def("toFormattedStringLocale", - (string(Epochstamp::*)(const string&, const string&, const string&) - const)(&Epochstamp::toFormattedStringLocale), - (bp::arg("localeName") = "", bp::arg("format") = "%Y-%b-%d %H:%M:%S", bp::arg("localTimeZone") = "Z")); - - e.def(bp::self != bp::self); - e.def(bp::self + bp::other()); - e.def(bp::self += bp::other()); - e.def(bp::self - bp::other()); - e.def(bp::self - bp::self); - e.def(bp::self -= bp::other()); - e.def(bp::self < bp::self); - e.def(bp::self <= bp::self); - - // karabo::util::Epochstamp::operator= - e.def("assign", (Epochstamp & (Epochstamp::*)(time_t const&))(&Epochstamp::operator=), (bp::arg("tm")), - bp::return_self<>()); - - - // karabo::util::Epochstamp::operator= - e.def("assign", (Epochstamp & (Epochstamp::*)(timeval const&))(&Epochstamp::operator=), (bp::arg("tv")), - bp::return_self<>()); - - - //::karabo::util::Epochstamp::operator= - e.def("assign", (Epochstamp & (Epochstamp::*)(timespec const&))(&Epochstamp::operator=), (bp::arg("ts")), - bp::return_self<>()); - - e.def(bp::self == bp::self); - e.def(bp::self > bp::self); - e.def(bp::self >= bp::self); -} diff --git a/src/karathon/PyUtilException.cc b/src/karathon/PyUtilException.cc deleted file mode 100644 index 324df8275f..0000000000 --- a/src/karathon/PyUtilException.cc +++ /dev/null @@ -1,69 +0,0 @@ -/** - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include -#include - -namespace bp = boost::python; - -// Translate C++ karabo::util::Exception into python RuntimeError exception -void translatorException(const karabo::util::Exception& e) { - // Assemble message from type, friendly message and - separated by \nDETAILS:\n" - detailed message. - std::string msg(e.type()); - msg += ": "; - msg += e.userFriendlyMsg(false); - msg += "\nDETAILS:\n"; - // Order of calls to userFriendlyMsg(false) and detailedMsg() matters since the latter clears the stack. - msg += e.detailedMsg(); - - // Pass C-pointer to Python - PyErr_SetString(PyExc_RuntimeError, msg.c_str()); -} - -void translatorRemoteException(const karabo::util::RemoteException& e) { - // Assemble message from both, friendly message and details with "\nDETAILS:" as separator - std::string msg(e.type()); - msg += ": "; - msg += e.userFriendlyMsg(true); // Clear stack - details() below is not using it (and it should be empty anyway...) - msg += "\nDETAILS: "; - msg += e.type(); // Contains instanceId where exception occurred, so repeat also in details - msg += ": "; - msg += e.details(); // See ErrorHandlerWrap::operator() concerning details() vs detailedMsg() - - // Pass C-pointer to Python - PyErr_SetString(PyExc_RuntimeError, msg.c_str()); -} - -void translatorTimeoutException(const karabo::util::TimeoutException& e) { - const std::string msg(e.userFriendlyMsg(true)); // Clear stack - - // Pass C-pointer to Python - PyErr_SetString(PyExc_TimeoutError, msg.c_str()); -} - -void exportPyUtilException() { - // Register exception translators - order seems relevant: - // First the base (to catch all not specifically mentioned), then the concrete ones. - bp::register_exception_translator(translatorException); - bp::register_exception_translator(translatorRemoteException); - bp::register_exception_translator(translatorTimeoutException); - // One could translate ParameterException to Python KeyError, but that does not well match: - // ParameterException is also used when other input than keys are bad. -} diff --git a/src/karathon/PyUtilHash.cc b/src/karathon/PyUtilHash.cc deleted file mode 100644 index e02e5b4396..0000000000 --- a/src/karathon/PyUtilHash.cc +++ /dev/null @@ -1,462 +0,0 @@ -/* $Id$ - * - * Author: , - * - * Created on February 29, 2012, 9:02 AM - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include -#include -#include - -#include "AttributesNodeWrap.hh" -#include "AttributesWrap.hh" -#include "HashWrap.hh" -#include "NodeWrap.hh" - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; -using namespace karathon; - -typedef karabo::util::Element > > - HashNode; - - -void exportPyUtilHash() { - // #ifdef WITH_BOOST_NUMPY - // bn::initialize(); - // #endif - - bp::docstring_options docs(true, true, false); - - // Types - bp::enum_("Types", - "This enumeration describes reference types supported in configuration system.") - .value("BOOL", PyTypes::BOOL) - .value("VECTOR_BOOL", PyTypes::VECTOR_BOOL) - .value("CHAR", PyTypes::CHAR) - .value("VECTOR_CHAR", PyTypes::VECTOR_CHAR) - .value("INT8", PyTypes::INT8) - .value("VECTOR_INT8", PyTypes::VECTOR_INT8) - .value("UINT8", PyTypes::UINT8) - .value("VECTOR_UINT8", PyTypes::VECTOR_UINT8) - .value("INT16", PyTypes::INT16) - .value("VECTOR_INT16", PyTypes::VECTOR_INT16) - .value("UINT16", PyTypes::UINT16) - .value("VECTOR_UINT16", PyTypes::VECTOR_UINT16) - .value("INT32", PyTypes::INT32) - .value("VECTOR_INT32", PyTypes::VECTOR_INT32) - .value("UINT32", PyTypes::UINT32) - .value("VECTOR_UINT32", PyTypes::VECTOR_UINT32) - .value("INT64", PyTypes::INT64) - .value("VECTOR_INT64", PyTypes::VECTOR_INT64) - .value("UINT64", PyTypes::UINT64) - .value("VECTOR_UINT64", PyTypes::VECTOR_UINT64) - .value("FLOAT", PyTypes::FLOAT) - .value("VECTOR_FLOAT", PyTypes::VECTOR_FLOAT) - .value("DOUBLE", PyTypes::DOUBLE) - .value("VECTOR_DOUBLE", PyTypes::VECTOR_DOUBLE) - .value("COMPLEX_FLOAT", PyTypes::COMPLEX_FLOAT) - .value("VECTOR_COMPLEX_FLOAT", PyTypes::VECTOR_COMPLEX_FLOAT) - .value("COMPLEX_DOUBLE", PyTypes::COMPLEX_DOUBLE) - .value("VECTOR_COMPLEX_DOUBLE", PyTypes::VECTOR_COMPLEX_DOUBLE) - .value("STRING", PyTypes::STRING) - .value("VECTOR_STRING", PyTypes::VECTOR_STRING) - .value("HASH", PyTypes::HASH) - .value("VECTOR_HASH", PyTypes::VECTOR_HASH) - .value("SCHEMA", PyTypes::SCHEMA) - .value("ANY", PyTypes::ANY) - .value("NONE", PyTypes::NONE) - .value("VECTOR_NONE", PyTypes::VECTOR_NONE) - .value("UNKNOWN", PyTypes::UNKNOWN) - .value("SIMPLE", PyTypes::SIMPLE) - .value("SEQUENCE", PyTypes::SEQUENCE) - .value("POINTER", PyTypes::POINTER) - .value("VECTOR_HASH_POINTER", PyTypes::VECTOR_HASH_POINTER) - .value("PYTHON", PyTypes::PYTHON_DEFAULT) - .value("NUMPY", PyTypes::NUMPY_DEFAULT); - - bp::class_("TypesClass", bp::no_init) - .def("to", (const karabo::util::Types::ReferenceType (*)(const PyTypes::ReferenceType&)) & PyTypes::to, - (bp::arg("Python_types"))) - .staticmethod("to") - .def("from", (const PyTypes::ReferenceType (*)(const karabo::util::Types::ReferenceType&)) & PyTypes::from, - (bp::arg("C++_types"))) - .staticmethod("from") - .def("category", (const PyTypes::ReferenceType (*)(int)) & PyTypes::category, (bp::arg("C++_types"))) - .staticmethod("category"); - - - bp::def("setStdVectorDefaultConversion", &HashWrap().setDefault, (bp::arg("PYTHON_or_NUMPY_types"))); - bp::def("isStdVectorDefaultConversion", &HashWrap().isDefault, (bp::arg("PYTHON_or_NUMPY_types"))); - - - // using boost::python::iterator; - // bp::def("range", &karathon::range); - - // bp::class_("HashAttributesMapIterator", bp::no_init); - // - // bp::class_("HashAttributesConstMapIterator", bp::no_init); - - bp::class_ > an("HashAttributesNode", - bp::no_init); - an.def("getKey", &AttributesNodeWrap().getKey, "Get key of current node in attribute's container"); - an.def("__str__", &AttributesNodeWrap().getKey); - an.def("setValue", &AttributesNodeWrap().setValue, (bp::arg("value")), - "Set value for current node in attribute's container"); - an.def("getValue", &AttributesNodeWrap().getValue, "Get value for current node in attribute's container"); - an.def("getValueAs", &AttributesNodeWrap().getValueAs, (bp::arg("type")), - "Get value as a type given as an argument for current node"); - an.def("getType", &AttributesNodeWrap().getType, "Get type of the value kept in current node"); - an.def("setType", &AttributesNodeWrap().setType, (bp::arg("type")), "Set type for value kept in current node"); - - - bp::class_ a( - "HashAttributes", - "The HashAttributes class is a heterogeneous container with string key and \"any object\" value\n" - "that preserves insertion order, i.e. it is behaving like an ordered map"); - // Constructor as empty attributes: - a.def(bp::init<>()); - // This would allow to put two items into the attributes - but as bp::object's without conversion to - // their C++ counterparts, so it is useless and skipped (for any number of key/value pairs) - // a.def(bp::init()); - a.def("has", &AttributesWrap().has, (bp::arg("key")), - "Returns True if HashAttributes container contains given \"key\""); - a.def("__contains__", &AttributesWrap().has, (bp::arg("key")), - "Returns True if HashAttributes container contains given \"key\""); - a.def("isType", &AttributesWrap().has, (bp::arg("key"), bp::arg("type")), - "Returns True if HashAttributes container has given \"key\" of reference \"type\".."); - a.def("erase", &AttributesWrap().erase, (bp::arg("key")), "Erase \"key\" attribute"); - a.def("__delitem__", &AttributesWrap().erase, (bp::arg("key")), "Erase \"key\" attribute"); - a.def("size", &AttributesWrap().size, "Returns number of entries in HashAttributes container"); - a.def("__len__", &AttributesWrap().size, "Returns number of entries in HashAttributes container"); - a.def("empty", &AttributesWrap().empty, "Returns True if HashAttributes container is empty."); - a.def("bool", &AttributesWrap().size, - "This function automatically called when HashAttributes object checked in \"if\" expression. \"False\" means " - "that container is empty."); - a.def("clear", &AttributesWrap().clear, "Make HashAttributes container empty."); - a.def("getNode", &AttributesWrap().getNode, (bp::arg("key")), - "Returns HashAttributesNode object associated with \"key\" attribute."); - a.def("get", &AttributesWrap().get, (bp::arg("key")), "Returns value for \"key\" attribute."); - a.def("__getitem__", &AttributesWrap().__getitem__, (bp::arg("key")), - "Pythonic style for getting value of attribute: x = attrs['abc']"); - a.def("getAs", &AttributesWrap().getAs, (bp::arg("key"), bp::arg("type")), - "Get the value of the \"key\" attribute and convert it to type \"type\"."); - a.def("set", &AttributesWrap().set, (bp::arg("key"), bp::arg("value")), "Set the \"value\" for \"key\" attribute."); - a.def("__setitem__", &AttributesWrap().set, (bp::arg("key"), bp::arg("value")), - "Pythonic style for setting value of attribute: attrs['abc'] = 123"); - // a.def("find", &AttributesWrap().find, (bp::arg("key")), ""); - // a.def("getIt", &AttributesWrap().getIt, (bp::arg("it"))); - a.def("__iter__", bp::iterator >()); - - bp::class_ > n("HashNode", bp::init<>()); - n.def("__repr__", &NodeWrap().getKey); - n.def("__str__", &NodeWrap().getKey); - n.def("getKey", &NodeWrap().getKey, "Returns the key of current node."); - n.def("setValue", &NodeWrap().setValue, (bp::arg("value")), "Sets the new value of current node."); - n.def("getValue", &NodeWrap().getValue, "Gets the value of current node."); - n.def("getValueAs", &NodeWrap().getValueAs, (bp::arg("type")), - "Gets the value of current node converted to given reference type"); - n.def("setAttribute", &NodeWrap().setAttribute, (bp::arg("key"), bp::arg("value")), - "Sets the \"key\" attribute to some \"value\" in current node."); - n.def("getAttribute", &NodeWrap().getAttribute, (bp::arg("key")), - "Gets the value of \"key\" attribute in current node."); - n.def("getAttributeAs", &NodeWrap().getAttributeAs, (bp::arg("key"), bp::arg("type")), - "Gets the value of \"key\" attribute converted to type \"type\"."); - n.def("hasAttribute", &NodeWrap().hasAttribute, (bp::arg("key")), - "Check that current node has the \"key\" attribute."); - n.def("setAttributes", &NodeWrap().setAttributes, (bp::arg("attributes")), - "Sets new set of attributes in current node."); - n.def("getAttributes", &NodeWrap().getAttributes, bp::return_internal_reference<1>(), - "Gets all attributes in current node as HashAttributes object. This object is internal reference not a " - "copy."); - n.def("copyAttributes", &NodeWrap().copyAttributes, - "Gets a copy of all attributes in current node as HashAttributes object."); - n.def("getType", &NodeWrap().getType, "Gets the value type as a reference type"); - n.def("setType", &NodeWrap().setType, (bp::arg("type")), "Sets the value type as a reference \"type\"."); - - - bp::enum_("HashMergePolicy", "This enumeration defines possible options when merging 2 hashes.") - .value("MERGE_ATTRIBUTES", Hash::MERGE_ATTRIBUTES) - .value("REPLACE_ATTRIBUTES", Hash::REPLACE_ATTRIBUTES); - - bp::class_ > h("Hash", - "The Hash class can be regarded as a generic hash container, which " - "associates a string key to a value of any type.\n" - "Optionally attributes of any value-type can be associated to each " - "hash-key. The Hash preserves insertion order. The Hash\n" - "class is much like a XML-DOM container with the difference of " - "allowing only unique keys on a given tree-level."); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def(bp::init()); - h.def("clear", &Hash::clear, "h.clear() makes empty the content of current Hash object 'h' (in place).\n"); - h.def("empty", &HashWrap().empty, "h.empty() -> True if 'h' is empty otherwise False.\n"); - h.def("getKeys", (void (*)(const karabo::util::Hash&, const bp::object&)) & HashWrap().getKeys, - (bp::arg("target_container")), - "This function follows the API of C++ counterpart. Put into the target container all the keys visible\n" - "on the top level of the tree hierarchy.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tmykeys = []\n\th.getKeys(mykeys)\nprint mykeys\n\n... returns:\n\t['a', 'b', 'c']\n"); - h.def("getKeys", &HashWrap().keys, - "Returns list of all keys visible on the top level of the tree hierarchy.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.getKeys()\n\n... returns:\n\t['a', 'b', 'c']\n"); - h.def("keys", &HashWrap().keys, - "Returns list of all keys visible on the top level of the tree hierarchy.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.keys()\n\n... returns:\n\t['a', 'b', 'c']\n"); - h.def("getValues", &HashWrap().getValues, - "Returns list of values associated with keys visible on the top level of the tree hierarchy.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.getValues()\n\n... returns:\n\t[,\n\t ,\n" - "\t [True, False, True, True]]\n"); - - h.def("values", &HashWrap().getValues, - "Returns list of values associated with keys visible on the top level of the tree hierarchy.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.values()\n\n... returns:\n\t[,\n\t ,\n" - "\t [True, False, True, True]]\n"); - h.def("getPaths", &HashWrap().getPaths, (bp::arg("target_container")), - "Put into the target container the full paths of current Hash object.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tmypaths = []\n\th.getPaths(mypaths)\nprint mypaths\n\n... returns:\n\t['a.b.c', 'b.x', 'b.y', 'c']"); - h.def("getPaths", &HashWrap().paths, - "Returns list of all the paths being in current Hash object.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.getPaths()\n\n... returns:\n\t['a.b.c', 'b.x', 'b.y', 'c']"); - h.def("paths", &HashWrap().paths, - "Returns list of all the paths being in current Hash object.\n" - "\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n" - "\tprint h.paths()\n\n... returns:\n\t['a.b.c', 'b.x', 'b.y', 'c']"); - h.def("set", &HashWrap().set, (bp::arg("path"), bp::arg("value"), bp::arg("sep") = "."), - "Set the new 'path'/'value' pair into the current Hash object. The third optional parameter is a separator,\n" - "used to form a tree hierarchy out of 'path'.\nExample:\n\th = Hash()\n\th.set('a.b.c', 1)\n\th.set('x/y/z', " - "2, \"/\")\n" - "\th.set('u/v/w', 3)\n\tprint h"); - h.def("__setitem__", &HashWrap().set, (bp::arg("path"), bp::arg("value"), bp::arg("sep") = "."), - "h[path] = value <==> h.set(path, value)\nUse this setting of the new path/value item if the default " - "separator fits." - "\nExample:\n\th = Hash()\n\th['a.b.c'] = 1\n\th.set('x/y/z', 2, \"/\")\n\th['u/v/w'] = 3\n\tprint h"); - h.def("setAs", &HashWrap().setAs, (bp::arg("path"), bp::arg("value"), bp::arg("type"), bp::arg("sep") = "."), - "h.setAs(path, value, type)\nUse this method if the C++ value type cannot be deduced properly of python value" - "\nExample:\n\th = Hash()\n\th.setAs('a.b.c', 1L, Types.UINT64)\n\tprint h"); - h.def("get", &HashWrap().get, (bp::arg("path"), bp::arg("sep") = ".", bp::arg("default") = bp::object()), - "Get the 'value' by 'path'. Optionally, the separator can be defined as second argument.\n" - "If you want to emulate the Python dictionary get() method, a default return value can be " - "passed using the 'default' keyword argument." - "Example:\n\th = Hash('a.b.c', 1)\n\tprint h.get('a/b/c','/')"); - h.def("__getitem__", &HashWrap().getRef, (bp::arg("iterator"), bp::arg("sep") = "."), - "Use this form of getting the 'value' using the 'path' if you need the default separator.\n" - "Example:\n\th = Hash('a.b.c', 1)\n\tprint h['a.b.c']"); - h.def("has", &HashWrap().has, (bp::arg("path"), bp::arg("sep") = "."), - "Returns true if given 'path' is found in current Hash object. Use separator as needed."); - h.def("__contains__", &HashWrap().has, (bp::arg("path"), bp::arg("sep") = "."), - "Check if 'path' is known in current Hash object. Use this form if you use the default separator.\n" - "Example:\n\th = Hash('a.b.c', 1)\n\t...\n\tif 'a.b.c' in h:\n\t\th['a.b.c'] = 2"); - h.def("erase", &HashWrap().erase, (bp::arg("path"), bp::arg("sep") = "."), - "h.erase(path) -> remove item identified by 'path' from 'h' if it exists (in place)\n" - "Returns True if path is found, otherwise False\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\tprint h\n\t" - "del h['b.x']\n\tprint h\n\th.erase('b.y')\n\tprint h\n\tdel h['b']"); - h.def("__delitem__", &HashWrap().erase, (bp::arg("path"), bp::arg("sep") = "."), - "del h[path] <==> h.erase(path)\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\tprint h\n\t" - "del h['b.x']\n\tprint h\n\th.erase('b.y')\n\tprint h\n\tdel h['b']"); - h.def("erasePath", &HashWrap().erasePath, (bp::arg("path"), bp::arg("sep") = "."), - "h.erase(path) -> remove item identified by 'path' from 'h' (in place)\nExample:\n" - "\th = Hash('a[0].b[0].c', 1, 'b[0].c.d', 2, 'c.d[0].e', 3, 'd.e', 4, 'e', 5, 'f.g.h.i.j.k', 6)\n\tprint " - "h\n\t" - "h.erasePath['a[0].b[0].c']\n\tprint h\n\th.erasePath('b[0].c.d')\n\tprint h\n\th.erasePath['c.d[0].e']"); - h.def("__len__", &Hash::size, - "h.__len__() -> number of (top level) items of Hash mapping <==> len(h) <==> len(h.keys())"); - h.def("bool", &Hash::size); - h.def("__iter__", bp::iterator >(), - "h.__iter__() <==> iter(h) : iterator of (top level) items of 'h' mapping.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\ti = iter(h) # create iterator\n\t" - "n = i.next() # position to the 1st node\n\tprint n.getKey()\n\tprint n.getValue()\n\t" - "n = i.next() # position to the 2nd node\n\t...\n\nExample2:\n\t" - "for n in h:\n\t\tprint n.getKey()\n\t\tprint.getValue()"); - h.def("getAs", &HashWrap().getAs, (bp::arg("path"), bp::arg("type"), bp::arg("sep") = "."), - "Get value by 'path' and convert it to 'type' type. Optionally use separator.\n" - "Example:\n\th = Hash('a.b.c', True)\n\tprint h.getAs('a.b.c', Types.INT32)\n\t" - "print h.getAs('a.b.c', Types.STRING)\n\tprint h.getAs('a.b.c', Types.DOUBLE)"); - h.def("getType", &HashWrap().getType, (bp::arg("path"), bp::arg("sep") = "."), - "Get type by 'path'. Returns 'Types.' object.\n" - "Example:\n\th = Hash('a.b.c', True)\n\tprint h.getType('a.b.c')"); - h.def("merge", &HashWrap().merge, - (bp::arg("hash"), bp::arg("policy") = Hash::REPLACE_ATTRIBUTES, bp::arg("selectedPaths") = bp::object(), - bp::arg("sep") = "."), - "h.merge(h2) <==> h += h2 : merging 'h2' into 'h'.\n\nBut merge allows to specify more details:\n" - "policy: REPLACE_ATTRIBUTES or MERGE_ATTRIBUTES\n" - "selectedPaths: an iterable of paths in h2 to select\n" - " (None means to select all)\n" - "sep: single letter between keys in paths of nested Hash"); - // h.def("__add__", &Hash::operator+, (bp::arg("hash1"), bp::arg("hash2")), - // bp::return_value_policy()); - h.def("__iadd__", &Hash::operator+=, (bp::arg("hash")), bp::return_internal_reference<>(), - "This form of merging is preferable.\nExample:\n" - "\th = Hash('a.b1.c', 22)\n\th2 = Hash('a.b2.c', 33)\n\th += h2"); - h.def("subtract", &Hash::subtract, (bp::arg("hash")), "h.subtract(h2) <==> h -= h2 : subtracting 'h2' from 'h'"); - // h.def("__add__", &Hash::operator+, (bp::arg("hash1"), bp::arg("hash2")), - // bp::return_value_policy()); - h.def("__isub__", &Hash::operator-=, (bp::arg("hash")), bp::return_internal_reference<>(), - "This form of subtracting is preferable.\nExample:\n" - "\th = Hash('a.b.c', 22, 'a.b.d', 33, 'a.c.d', 44)\n\th2 = Hash('a.b', Hash())\n\th -= h2"); - - // Global free function to compare Hash, vector, Hash::Node, Schema - def("similar", &similarWrap, (bp::arg("left"), bp::arg("right")), - "Compares two hashes for similar structure.\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "flat = Hash()\n\th.flatten(flat) # 'flat' will contain 'flatten' hash\n\t" - "tree = Hash()\n\tflat.unflatten(tree)\n\tresult = similar(h, tree)\n" - "... result will be 'True'"); - - // Global free function to compare Hash, // TODO: could be extended for vector, Hash::Node or Schema - def("fullyEqual", &fullyEqualWrap, (bp::arg("left"), bp::arg("right"), bp::arg("orderMatters") = true), - "Compares two hashes for exact equality: keys, types, attributes, values\n" - "If orderMatters is True (default) also the order of keys matters."); - - h.def("isType", &HashWrap().is, (bp::arg("path"), bp::arg("type"), bp::arg("sep") = "."), - "h.isType(path, type) -> True if reference type of value in Hash container for given 'path' is equal " - "'type'.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "assert h.isType('a.b.c', Types.INT32) == True\n\t" - "assert h.isType('b.y', Types.DOUBLE) == True\n\t" - "assert h.isType('c', Types.VECTOR_INT32) == True"); - h.def(bp::self_ns::str(bp::self)); - h.def(bp::self_ns::repr(bp::self)); - // h.def("copy", &HashWrap().pyDict2Hash, (bp::arg("dict"), bp::arg("sep") = "."), - // bp::return_value_policy ()); - // h.def("update", &Hash::update, (bp::arg("hash"))); - h.def("flatten", &HashWrap().flatten, (bp::arg("flat"), bp::arg("sep") = "."), - "Make all key/value pairs flat and put them into 'target' container. Optionally a separator can be " - "used.\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "flat = Hash()\n\th.flatten(flat) # 'flat' will contain 'flatten' hash\n\t" - "tree = Hash()\n\tflat.unflatten(tree)\n\tresult = similar(h, tree)\n" - "... result will be 'True'"); - h.def("unflatten", &HashWrap().unflatten, (bp::arg("tree"), bp::arg("sep") = "."), - "Make all key/value pairs tree-like structured and put them into 'target' container. Optionally use " - "separator.\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "flat = Hash()\n\th.flatten(flat) # 'flat' will contain 'flatten' hash\n\t" - "tree = Hash()\n\tflat.unflatten(tree)\n\tresult = similar(h, tree)\n" - "... result will be 'True'"); - h.def("find", &HashWrap().find, (bp::arg("path"), bp::arg("sep") = "."), - "Find node in current Hash using \"path\". Optionally the separator \"sep\" may be defined.\n" - "Returns not a copy but reference to the existing Hash.Node object or \"None\".\n" - "If you do any changes via returned object, these changes will be reflected in the current Hash object.\n" - "Example:\n\th = Hash('a.b.c', 1)\n\tnode = h.find('a.b.c')\n\tif node is not None: node.setValue(2)"); - h.def("setNode", &HashWrap().setNode, (bp::arg("node")), - "Set \"node\" into current Hash object. You cannot create node directly, you can extract the node from " - "created Hash object.\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "n = h.getNode('b')\n\tg = Hash()\n\tg.setNode(n)\n\tprint g"); - h.def("getNode", &HashWrap().getNode, - (bp::arg("path"), bp::arg("sep") = "."), // bp::return_internal_reference<1> (), - "Returns a reference of found node (not a copy!), so if you do any changes via returned object,\n" - "these changes will be reflected in the current Hash object.\nExample:\n" - "\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "n = h.getNode('b')\n\tg = Hash()\n\tg.setNode(n)\n\tprint g"); - h.def("hasAttribute", &HashWrap().hasAttribute, (bp::arg("path"), bp::arg("attribute"), bp::arg("sep") = "."), - "Returns true if the questioned attribute exists, else returns false."); - h.def("getAttribute", &HashWrap().getAttribute, (bp::arg("path"), bp::arg("attribute"), bp::arg("sep") = "."), - "Get attribute value following given 'path' and 'attribute' name. Optionally use separator.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\th.setAttribute('a.b.c', 'attr1', " - "[1.234,2.987,5.555]\n\t" - "assert h.getAttribute('a.b.c', 'attr1') == [1.234,2.987,5.555]"); - h.def("getAttributeAs", &HashWrap().getAttributeAs, - (bp::arg("path"), bp::arg("attribute"), bp::arg("type"), bp::arg("sep") = "."), - "h.getAttributeAs(path, attribute, type, sep = '.') -> value of 'type' type.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\th.setAttribute('a.b.c', 'attr1', " - "[1.234,2.987,5.555])\n" - "\nHere you have to be sure that you have imported numpy as np:\n\n\timport numpy as np\n\t" - "assert h.getAttributeAs('a.b.c', 'attr1', Types.NDARRAY).all() == np.array([1.234,2.987,5.555], " - "dtype=np.double).all()"); - h.def("getAttributes", &HashWrap().getAttributes, (bp::arg("path"), bp::arg("sep") = "."), - bp::return_internal_reference<1>(), - "h.getAttributes(path, sep='.') -> iterable container of attributes which is an internal reference, not a " - "copy.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "h.setAttribute('a.b.c', 'attr1', [1.234,2.987,5.555])\n\th.setAttribute('a.b.c', 'attr2', 1)\n\t" - "h.setAttribute('a.b.c', 'attr3', False)\n\t" - "for a in h.getAttributes('a.b.c'):\n\t\tprint a.getKey(), a.getValue()\n\t" - "attrs = h.getAttributes('a.b.c')\n\tattrs['attr2'] = 2\n\t" - "assert h.getAttribute('a.b.c', 'attr2') == 2"); - h.def("copyAttributes", &HashWrap().copyAttributes, (bp::arg("path"), bp::arg("sep") = "."), - "h.copyAttributes(path, sep='.') -> iterable container of attributes.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "h.setAttribute('a.b.c', 'attr1', [1.234,2.987,5.555])\n\th.setAttribute('a.b.c', 'attr2', 1)\n\t" - "h.setAttribute('a.b.c', 'attr3', False)\n\t" - "for a in h.copyAttributes('a.b.c'):\n\t\tprint a.getKey(), a.getValue()" - "attrs = h.copyAttributes('a.b.c')\n\tattrs['attr2'] = 2\n\t" - "assert h.getAttribute('a.b.c', 'attr2') == 1"); - h.def("setAttribute", &HashWrap().setAttribute, - (bp::arg("path"), bp::arg("attribute"), bp::arg("value"), bp::arg("sep") = "."), - "Set attribute associated with path.\nExample:\n\th = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', " - "[1,2,3])\n\t" - "h.setAttribute('a.b.c', 'attr1', [1.234,2.987,5.555])\n\tassert h.getAttribute('a.b.c', 'attr1') == " - "[1.234,2.987,5.555]"); - h.def("setAttributes", &HashWrap().setAttributes, (bp::arg("path"), bp::arg("attributes"), bp::arg("sep") = "."), - "h.setAttributes(path, attributes, sep='.') allows to associate 'attributes' with 'path' in this " - "Hash.\nExample:\n\t" - "h = Hash('a.b.c', 1, 'b.x', 2.22, 'b.y', 7.432, 'c', [1,2,3])\n\t" - "h.setAttribute('a.b.c', 'attr1', [1.234,2.987,5.555])\n\th.setAttribute('a.b.c', 'attr2', 1)\n\t" - "h.setAttribute('a.b.c', 'attr3', False)\n\ta = h.getAttributes('a.b.c')\n\t" - "h.setAttributes('c', a) # copy attributes under the different path"); - h.def("__copy__", &HashWrap().copy); - h.def("__deepcopy__", &HashWrap().copy); - h.def(bp::self == bp::self); - h.def(bp::self != bp::self); - - - struct VectorHashPickleSuite : bp::pickle_suite { - static bp::tuple getstate(const std::vector& vec) { - return Wrapper::fromStdVectorToPyTuple(vec); - } - - - static void setstate(std::vector& vec, bp::tuple state) { - vec = Wrapper::fromPyTupleToStdVector(state); - } - }; - - bp::class_, boost::shared_ptr > >("VectorHash") - .def(bp::vector_indexing_suite >()) - .def_pickle(VectorHashPickleSuite()); // enables copy.copy of VectorHash - - bp::class_ >, boost::shared_ptr > > >( - "VectorHashPointer") - .def(bp::vector_indexing_suite >, true>()); -} diff --git a/src/karathon/PyUtilJsonToHashParser.cc b/src/karathon/PyUtilJsonToHashParser.cc deleted file mode 100644 index baf8baf55f..0000000000 --- a/src/karathon/PyUtilJsonToHashParser.cc +++ /dev/null @@ -1,27 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -namespace bp = boost::python; - -void exportPyUtilJsonToHashParser() { - bp::def("jsonToHash", &karabo::util::jsonToHash); - bp::def("generateAutoStartHash", &karabo::util::generateAutoStartHash); -} diff --git a/src/karathon/PyUtilNDArray.cc b/src/karathon/PyUtilNDArray.cc deleted file mode 100644 index c328fbceed..0000000000 --- a/src/karathon/PyUtilNDArray.cc +++ /dev/null @@ -1,29 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include - -#include "Wrapper.hh" - -namespace bp = boost::python; -using namespace karathon; - -void exportPyUtilNDArray() { - bp::class_ > d("_CppArrayRefHandler_", - bp::init()); -} diff --git a/src/karathon/PyUtilRollingWindowStatistics.cc b/src/karathon/PyUtilRollingWindowStatistics.cc deleted file mode 100644 index 9189a2d628..0000000000 --- a/src/karathon/PyUtilRollingWindowStatistics.cc +++ /dev/null @@ -1,38 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - - -namespace bp = boost::python; -using namespace karabo::util; - - -void exportPyUtilRollingWindowStatistics() { - bp::class_, boost::noncopyable> d( - "RollingWindowStatistics", bp::no_init); - d.def(bp::init(bp::args("evaluationInterval"))); - d.def("update", &RollingWindowStatistics::update, bp::arg("value")); - d.def("getRollingWindowVariance", &RollingWindowStatistics::getRollingWindowVariance); - d.def("getRollingWindowMean", &RollingWindowStatistics::getRollingWindowMean); -} diff --git a/src/karathon/PyUtilSchema.cc b/src/karathon/PyUtilSchema.cc deleted file mode 100644 index 93b9a0e3d6..0000000000 --- a/src/karathon/PyUtilSchema.cc +++ /dev/null @@ -1,2518 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "PythonMacros.hh" -#include "Wrapper.hh" -#include "boost/python/raw_function.hpp" - -namespace bp = boost::python; -using namespace karabo::util; -using namespace karabo::io; -using namespace std; - - -struct SchemaWrapper : Schema, bp::wrapper { - SchemaWrapper(Schema const& arg) : Schema(arg), bp::wrapper() {} - - - SchemaWrapper() : Schema(), bp::wrapper() {} - - - SchemaWrapper(std::string const& classId, Schema::AssemblyRules const& rules) - : Schema(classId, boost::ref(rules)), bp::wrapper() {} - - - virtual ClassInfo getClassInfo() const { - if (bp::override func_getClassInfo = this->get_override("getClassInfo")) return func_getClassInfo(); - else return this->Schema::getClassInfo(); - } - - - ClassInfo default_getClassInfo() const { - return Schema::getClassInfo(); - } -}; - - -class ValidatorWrap { - public: - static bp::tuple validate(Validator& self, const Schema& schema, const Hash& configuration, - const bp::object& stamp) { - Hash::Pointer validated = Hash::Pointer(new Hash); - Timestamp tstamp; - if (stamp.ptr() != Py_None && bp::extract(stamp).check()) { - tstamp = bp::extract(stamp); - } - - pair result = self.validate(schema, configuration, *validated, tstamp); - bp::tuple t = bp::make_tuple(result.first, result.second, bp::object(validated)); - return t; - } - - - static void setValidationRules(Validator& self, const bp::object& obj) { - if (bp::extract(obj).check()) { - const Validator::ValidationRules& rules = bp::extract(obj); - self.setValidationRules(rules); - } - } - - - static bp::object getValidationRules(Validator& self) { - return bp::object(self.getValidationRules()); - } - - - static bp::object hasReconfigurableParameter(Validator& self) { - return bp::object(self.hasReconfigurableParameter()); - } - - - static const RollingWindowStatistics& getRollingStatistics(Validator& self, const std::string& path) { - return *self.getRollingStatistics(path); - } -}; - - -struct NodeElementWrap { - static NodeElement& appendParametersOfConfigurableClass(NodeElement& self, const bp::object& baseobj, - const std::string& classId) { - if (!PyType_Check(baseobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'arg1' given in 'appendParametersOfConfigurableClass(arg1, arg2)' of NODE_ELEMENT must be " - "a class in Python registered as base class in Configurator"); - } - if (!PyObject_HasAttrString(baseobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION("Class with classid = '" + classId + - "' given in 'appendParametersOfConfigurableClass(base, classid)' of " - "NODE_ELEMENT has no 'getSchema' method."); - } - std::string baseClassId; - if (PyObject_HasAttrString(baseobj.ptr(), "__karabo_cpp_classid__")) { - // baseobj is object of C++ base class - baseClassId = bp::extract(baseobj.attr("__karabo_cpp_classid__")); - } else { - baseClassId = bp::extract(baseobj.attr("__classid__")); - } - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - self.getNode().setAttribute(KARABO_SCHEMA_CLASS_ID, classId); - self.getNode().setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, baseClassId); - - bp::object schemaObj = baseobj.attr("getSchema")(classId); - - const Schema schema = bp::extract(schemaObj); - const Hash h = schema.getParameterHash(); - self.getNode().setValue(h); - - return self; - } - - - static NodeElement& appendParametersOf(NodeElement& self, const bp::object& obj) { - if (!PyType_Check(obj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'arg' given in 'appendParametersOf(arg)' of NODE_ELEMENT must be a class in Python"); - } - - std::string classId(bp::extract(obj.attr("__name__"))); - - Schema::Pointer schema(new Schema()); - obj.attr("expectedParameters")(schema); - self.getNode().setValue(schema->getParameterHash()); - self.getNode().setAttribute(KARABO_SCHEMA_CLASS_ID, classId); - self.getNode().setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, classId); - return self; - } - - - static NodeElement& appendSchema(NodeElement& self, const bp::object& schemaObj) { - if (!bp::extract(schemaObj).check()) throw KARABO_PYTHON_EXCEPTION("Argument is not a Schema object."); - const Schema schemaPy = bp::extract(schemaObj); - const Hash h = schemaPy.getParameterHash(); - self.getNode().setValue(h); - return self; - } - - static NodeElement& setDaqDataType(NodeElement& self, const bp::object& dataTypeObj) { - bp::extract getDaqType(dataTypeObj); - if (!getDaqType.check()) { - throw KARABO_PYTHON_EXCEPTION("Argument is not a DaqDataType object."); - } - const DaqDataType dataType = getDaqType(); - return self.setDaqDataType(dataType); - } - - static NodeElement& setSpecialDisplayType(NodeElement& self, const std::string& displayType) { - self.setSpecialDisplayType(displayType); - return self; - } - - - static NodeElement& setAllowedActions(NodeElement& self, const bp::object& actions) { - // Accept any Python iterable that provides strings - return self.setAllowedActions(karathon::Wrapper::fromPyIterableToCppContainer(actions)); - } -}; - - -struct ChoiceElementWrap { - static ChoiceElement& appendNodesOfConfigurationBase(ChoiceElement& self, const bp::object& classobj) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'arg' given in 'appendNodesOfConfigurationBase(arg)' of CHOICE_ELEMENT must be a class in " - "Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'appendNodesOfConfigurationBase' of CHOICE_ELEMENT must have 'getSchema' function"); - } - // TODO This whole code block repeats over and over!! TERRIBLE!! Cleaning needed. - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - Hash& choiceOfNodes = self.getNode().getValue(); - - bp::object nodeNameList = classobj.attr("getRegisteredClasses")(); - boost::any any; - karathon::Wrapper::toAny(nodeNameList, any); - - if (any.type() != typeid(std::vector)) - throw KARABO_PYTHON_EXCEPTION("getRegisteredClasses() doesn't return vector!"); - const vector& nodeNames = boost::any_cast>(any); - for (size_t i = 0; i < nodeNames.size(); i++) { - std::string nodeName = nodeNames[i]; - bp::object schemaObj = classobj.attr("getSchema")(nodeName, bp::object(Schema::AssemblyRules())); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - } - return self; - } - - - static ChoiceElement& appendAsNode(ChoiceElement& self, const bp::object& classobj, - const std::string& nodeNameObj) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'classobj' given in 'appendAsNode(classobj, nodeName)' of CHOICE_ELEMENT must be a class " - "in Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'appendAsNode(classobj, nodeName)' of CHOICE_ELEMENT has no 'getSchema' method"); - } - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - Hash& choiceOfNodes = self.getNode().getValue(); - string nodeName = nodeNameObj; - if (nodeNameObj == "") nodeName = classid; - bp::object schemaObj = classobj.attr("getSchema")(nodeName, bp::object(Schema::AssemblyRules())); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - return self; - } -}; - - -struct ListElementWrap { - static ListElement& appendNodesOfConfigurationBase(ListElement& self, const bp::object& classobj) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'arg' given in 'appendNodesOfConfigurationBase(arg)' of LIST_ELEMENT must be a class in " - "Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'appendNodesOfConfigurationBase' of LIST_ELEMENT has no 'getSchema' method"); - } - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - Hash& choiceOfNodes = self.getNode().getValue(); - - bp::object nodeNameList = classobj.attr("getRegisteredClasses")(); - boost::any any; - karathon::Wrapper::toAny(nodeNameList, any); - - if (any.type() != typeid(vector)) - throw KARABO_PYTHON_EXCEPTION("getRegisteredClasses() doesn't return vector!"); - const vector& nodeNames = boost::any_cast>(any); - for (size_t i = 0; i < nodeNames.size(); i++) { - std::string nodeName = nodeNames[i]; - bp::object schemaObj = classobj.attr("getSchema")(nodeName, Schema::AssemblyRules()); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - } - return self; - } - - - static ListElement& appendAsNode(ListElement& self, const bp::object& classobj, const std::string& name) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'classobj' given in 'appendAsNode(classobj, nodeName)' of LIST_ELEMENT must be a class in " - "Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'appendAsNode(classobj, nodeName)' of LIST_ELEMENT has no 'getSchema' method"); - } - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - Hash& choiceOfNodes = self.getNode().getValue(); - string nodeName = name; - if (nodeName == "") nodeName = classid; - bp::object schemaObj = classobj.attr("getSchema")(nodeName, Schema::AssemblyRules()); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - return self; - } - - typedef DefaultValue> DefListElement; - - - static ListElement& defaultValueList(DefListElement& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - vector v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.defaultValue(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the defaultValue of LIST_ELEMENT must be a list of strings"); - } - } -}; - - -struct InputElementWrap { - static InputElement& setInputType(InputElement& self, const bp::object& classobj) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'classobj' given in 'setInputType(classobj)' of INPUT_ELEMENT must be a class in Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'setInputType(classobj)' of INPUT_ELEMENT has no 'getSchema' method"); - } - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - Hash& choiceOfNodes = self.getNode().getValue(); - - bp::object nodeNameList = classobj.attr("getRegisteredClasses")(); - boost::any any; - karathon::Wrapper::toAny(nodeNameList, any); - - if (any.type() != typeid(vector)) - throw KARABO_PYTHON_EXCEPTION("getRegisteredClasses() doesn't return vector!"); - const vector& nodeNames = boost::any_cast>(any); - for (size_t i = 0; i < nodeNames.size(); i++) { - std::string nodeName = nodeNames[i]; - bp::object schemaObj = classobj.attr("getSchema")(nodeName); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, "Input-" + nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - } - return self; - } -}; - - -struct OutputElementWrap { - static OutputElement& setOutputType(OutputElement& self, const bp::object& classobj) { - if (!PyType_Check(classobj.ptr())) { - throw KARABO_PYTHON_EXCEPTION( - "Argument 'classobj' given in 'setOutputType(classobj)' of OUTPUT_ELEMENT must be a class in Python"); - } - if (!PyObject_HasAttrString(classobj.ptr(), "getSchema")) { - throw KARABO_PYTHON_EXCEPTION( - "Class given in 'setOutputType(classobj)' of OUTPUT_ELEMENT has no 'getSchema' method"); - } - std::string classid; - if (PyObject_HasAttrString(classobj.ptr(), "__karabo_cpp_classid__")) { - classid = bp::extract(classobj.attr("__karabo_cpp_classid__")); - } else { - classid = bp::extract(classobj.attr("__classid__")); - } - if (self.getNode().getType() != Types::HASH) self.getNode().setValue(Hash()); - // Retrieve reference for filling - Hash& choiceOfNodes = self.getNode().getValue(); - - bp::object nodeNameList = classobj.attr("getRegisteredClasses")(); - boost::any any; - karathon::Wrapper::toAny(nodeNameList, any); - - if (any.type() != typeid(vector)) - throw KARABO_PYTHON_EXCEPTION("getRegisteredClasses() doesn't return vector!"); - const vector& nodeNames = boost::any_cast>(any); - for (size_t i = 0; i < nodeNames.size(); i++) { - std::string nodeName = nodeNames[i]; - bp::object schemaObj = classobj.attr("getSchema")(nodeName); - const Schema& schema = bp::extract(schemaObj); - Hash::Node& node = choiceOfNodes.set(nodeName, schema.getParameterHash()); - node.setAttribute(KARABO_SCHEMA_CLASS_ID, nodeName); - node.setAttribute(KARABO_SCHEMA_DISPLAY_TYPE, "Output-" + nodeName); - node.setAttribute(KARABO_SCHEMA_NODE_TYPE, Schema::NODE); - node.setAttribute(KARABO_SCHEMA_ACCESS_MODE, WRITE); - } - return self; - } -}; - - -struct OverwriteElementWrap { - static OverwriteElement& setNewAlias(OverwriteElement& self, const bp::object& alias) { - boost::any any; - karathon::Wrapper::toAny(alias, any); - return self.setNewAlias(any); - } - - static OverwriteElement& setNewTags(OverwriteElement& self, const bp::object& tags) { - if (PyUnicode_Check(tags.ptr())) { - std::string tag = bp::extract(tags); - return self.setNewTags({tag}); - } - try { - return self.setNewTags(karathon::Wrapper::fromPyIterableToCppContainer(tags)); - } catch (...) { - throw KARABO_CAST_EXCEPTION("setNewTags expects new tags in a single str or a iterable of str"); - return self; // please compiler - } - } - - static OverwriteElement& setNewDefaultValue(OverwriteElement& self, const bp::object& value) { - const std::string className = bp::extract(value.attr("__class__").attr("__name__")); - if (className == "State") { - const std::string state = bp::extract(value.attr("name")); - return self.setNewDefaultValue(karabo::util::State::fromString(state)); - } else if (className == "AlarmCondition") { - const std::string condition = bp::extract(value.attr("value")); - return self.setNewDefaultValue(karabo::util::AlarmCondition::fromString(condition)); - } else { - boost::any any; - karathon::Wrapper::toAny(value, any); - return self.setNewDefaultValue(any); - } - } - - - static OverwriteElement& setNewMinInc(OverwriteElement& self, const bp::object& value) { - boost::any any; - karathon::Wrapper::toAny(value, any); - return self.setNewMinInc(any); - } - - - static OverwriteElement& setNewMaxInc(OverwriteElement& self, const bp::object& value) { - boost::any any; - karathon::Wrapper::toAny(value, any); - return self.setNewMaxInc(any); - } - - - static OverwriteElement& setNewMinExc(OverwriteElement& self, const bp::object& value) { - boost::any any; - karathon::Wrapper::toAny(value, any); - return self.setNewMinExc(any); - } - - - static OverwriteElement& setNewMaxExc(OverwriteElement& self, const bp::object& value) { - boost::any any; - karathon::Wrapper::toAny(value, any); - return self.setNewMaxExc(any); - } - - - static OverwriteElement& setNewMinSize(OverwriteElement& self, const bp::object& obj) { - try { - return self.setNewMinSize(karathon::Wrapper::toInteger(obj)); - } catch (const karabo::util::CastException& e) { - KARABO_RETHROW_AS(e); - return self; // please compiler - } - } - - - static OverwriteElement& setNewMaxSize(OverwriteElement& self, const bp::object& obj) { - try { - return self.setNewMaxSize(karathon::Wrapper::toInteger(obj)); - } catch (const karabo::util::CastException& e) { - KARABO_RETHROW_AS(e); - return self; // please compiler - } - } - - - static bp::object setNewAllowedStates(bp::tuple args, bp::dict kwargs) { - OverwriteElement& self = bp::extract(args[0]); - std::vector states; - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } - self.setNewAllowedStates(states); - return args[0]; - } - - - static bp::object setNewOptions(bp::tuple args, bp::dict kwargs) { - OverwriteElement& self = bp::extract(args[0]); - // get type of first arg - - bp::extract first_arg(args[1]); - if (first_arg.check()) { - self.setNewOptions(first_arg(), ",;"); - return args[0]; - } else { - // try states - std::vector states; - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string className = bp::extract(args[i].attr("__class__").attr("__name__")); - if (className == "State") { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } else { - throw KARABO_PYTHON_EXCEPTION( - "setNewOptions expects either a string or an arbitrary number of arguments of type State."); - } - } - self.setNewOptions(states); - return args[0]; - } - } -}; - - -struct ReadOnlySpecificTableWrap { - static ReadOnlySpecific>& initialValueTable( - ReadOnlySpecific>& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - vector v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.initialValue(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of initialValue for a read-only table must be a list of Hashes"); - } - } -}; - - -namespace tableElementWrap { - - - static bp::object allowedStatesPy(bp::tuple args, bp::dict kwargs) { - TableElement& self = bp::extract(args[0]); - std::vector states; - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } - self.allowedStates(states); - return args[0]; - } -} // namespace tableElementWrap - - -namespace schemawrap { - - - void setAlias(Schema& self, const bp::object& obj, const bp::object& aliasObj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - if (PyLong_Check(aliasObj.ptr())) { - int alias = bp::extract(aliasObj); - self.setAlias(path, alias); - } else if (PyUnicode_Check(aliasObj.ptr())) { - std::string alias = bp::extract(aliasObj); - self.setAlias(path, alias); - } else if (PyFloat_Check(aliasObj.ptr())) { - double alias = bp::extract(aliasObj); - self.setAlias(path, alias); - } else if (PyList_Check(aliasObj.ptr())) { - bp::ssize_t size = bp::len(aliasObj); - if (size == 0) { - std::vector alias = std::vector(); - self.setAlias(path, alias); - return; - } - bp::object list0 = aliasObj[0]; - if (list0.ptr() == Py_None) { - std::vector v; - for (bp::ssize_t i = 0; i < size; ++i) v.push_back(CppNone()); - self.setAlias(path, v); - return; - } - if (PyBool_Check(list0.ptr())) { - std::vector v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(aliasObj[i]); - } - self.setAlias(path, v); - return; - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(aliasObj[i]); - } - self.setAlias(path, v); - return; - } - if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(aliasObj[i]); - } - self.setAlias(path, v); - return; - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(aliasObj[i]); - } - self.setAlias(path, v); - return; - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(aliasObj[i]); - } - self.setAlias(path, v); - return; - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - bp::object str( - bp::handle<>(PyUnicode_AsUTF8String(static_cast(aliasObj[i]).ptr()))); - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(str.ptr(), &size); - v[i] = string(data, size); - } - self.setAlias(path, v); - return; - } - } else { - throw KARABO_PYTHON_EXCEPTION("Unknown data type of the 'alias' argument"); - } - } else throw KARABO_PYTHON_EXCEPTION("Python argument defining the key name in 'setAlias' should be a string"); - } - - - bp::object getParameterHash(const Schema& schema) { - return bp::object(schema.getParameterHash()); - } - - - karathon::PyTypes::ReferenceType getValueType(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - Types::ReferenceType t = schema.getValueType(path); - return karathon::PyTypes::from(t); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getValueType' must be a string"); - } - - //********************************************************************* - // Wrapper functions for : getMinInc, getMaxInc, getMinExc, getMaxExc * - //********************************************************************* - - - void setMinInc(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setMinInc(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setMinInc' must be a string"); - } - - - bp::object getMinInc(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_MIN_INC), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getMinInc' must be a string"); - } - - - void setMaxInc(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setMaxInc(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setMinInc' must be a string"); - } - - - bp::object getMaxInc(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_MAX_INC), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getMaxInc' must be a string"); - } - - - void setMinExc(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setMinExc(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setMinInc' must be a string"); - } - - - bp::object getMinExc(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_MIN_EXC), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getMinExc' must be a string"); - } - - - void setMaxExc(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setMaxExc(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setMinInc' must be a string"); - } - - - bp::object getMaxExc(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_MAX_EXC), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getMaxExc' must be a string"); - } - - //***************************************************************************** - // Wrapper functions for : getMinIncAs, getMaxIncAs, getMinExcAs, getMaxExcAs * - //***************************************************************************** - - - bp::object getMinIncAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getMinIncAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getMinIncAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getMinIncAs' must be a string"); - } - - - bp::object getMaxIncAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getMaxIncAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getMaxIncAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getMaxIncAs' must be a string"); - } - - - bp::object getMinExcAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getMinExcAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getMinExcAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getMinExcAs' must be a string"); - } - - - bp::object getMaxExcAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getMaxExcAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getMaxExcAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getMaxExcAs' must be a string"); - } - - - //***************************************************************************** - // Wrapper functions for : getWarnLow, getWarnHigh, getAlarmLow, getAlarmHigh * - //***************************************************************************** - - - void setWarnLow(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setWarnLow(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setWarnLow' must be a string"); - } - - - bp::object getWarnLow(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::WARN_LOW.asString()), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getWarnLow' must be a string"); - } - - - void setWarnHigh(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setWarnHigh(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setWarnHigh' must be a string"); - } - - - bp::object getWarnHigh(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::WARN_HIGH.asString()), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getWarnHigh' must be a string"); - } - - - void setAlarmLow(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setAlarmLow(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setAlarmLow' must be a string"); - } - - - bp::object getAlarmLow(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::ALARM_LOW.asString()), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAlarmLow' must be a string"); - } - - - void setAlarmHigh(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setAlarmHigh(path, any); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setAlarmHigh' must be a string"); - } - - - bp::object getAlarmHigh(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::ALARM_HIGH.asString()), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAlarmHigh' must be a string"); - } - - - void setWarnVarianceLow(Schema& self, const bp::object& obj, const double value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - self.setWarnVarianceLow(path, value); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setWarnVarianceLow' must be a string"); - } - - - bp::object getWarnVarianceLow(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::WARN_VARIANCE_LOW.asString()), - false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getWarnVarianceLow' must be a string"); - } - - - void setWarnVarianceHigh(Schema& self, const bp::object& obj, const double value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - self.setWarnVarianceHigh(path, value); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setWarnVarianceHigh' must be a string"); - } - - - bp::object getWarnVarianceHigh(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::WARN_VARIANCE_HIGH.asString()), - false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getWarnVarianceHigh' must be a string"); - } - - - void setAlarmVarianceLow(Schema& self, const bp::object& obj, const double value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - self.setAlarmVarianceLow(path, value); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setAlarmVarianceLow' must be a string"); - } - - - bp::object getAlarmVarianceLow(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, AlarmCondition::ALARM_VARIANCE_LOW.asString()), - false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAlarmVarianceLow' must be a string"); - } - - - void setAlarmVarianceHigh(Schema& self, const bp::object& obj, const double value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - self.setAlarmVarianceHigh(path, value); - } else throw KARABO_PYTHON_EXCEPTION("Python argument in 'setAlarmVarianceHigh' must be a string"); - } - - - bp::object getAlarmVarianceHigh(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject( - h.getAttributeAsAny(path, AlarmCondition::ALARM_VARIANCE_HIGH.asString()), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAlarmVarianceHigh' must be a string"); - } - - - //************************************************************************************* - // Wrapper functions for : getWarnLowAs, getWarnHighAs, getAlarmLowAs, getAlarmHighAs * - //************************************************************************************* - - - bp::object getWarnLowAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getWarnLowAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getWarnLowAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getWarnLowAs' must be a string"); - } - - - bp::object getWarnHighAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getWarnHighAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getWarnHighAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getWarnHighAs' must be a string"); - } - - - bp::object getAlarmLowAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getAlarmLowAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getAlarmLowAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getAlarmLowAs' must be a string"); - } - - - bp::object getAlarmHighAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - switch (pytype) { - case karathon::PyTypes::INT32: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getAlarmHighAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getAlarmHighAs(path)); - default: - break; - } - throw KARABO_PYTHON_EXCEPTION("Python Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION("Python first argument in 'getAlarmHighAs' must be a string"); - } - - - //*********************************************************************************** - // Wrapper functions for : getKeys, getPaths, getTags, getOptions, * - // getAllowedStates * - //*********************************************************************************** - - - bp::object getKeys(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - bp::list listParams; - string path = bp::extract(obj); - const vector& v = schema.getKeys(path); - for (size_t i = 0; i < v.size(); i++) listParams.attr("append")(bp::object(v[i])); - return listParams; - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getKeys' should be a string"); - } - - - bp::object getPaths(const Schema& schema) { - bp::list listParams; - const vector& v = schema.getPaths(); - for (size_t i = 0; i < v.size(); i++) listParams.attr("append")(bp::object(v[i])); - return listParams; - } - - - bp::object getTags(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const std::vector& v = schema.getTags(path); - return karathon::Wrapper::fromStdVectorToPyArray(v); - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getTags' should be a string"); - } - - struct ConvertOptions { - inline ConvertOptions(const string& path, const Schema& schema) : m_path(path), m_schema(schema) {} - - template - inline void operator()(T*) { - result = karathon::Wrapper::fromStdVectorToPyArray(m_schema.getOptions(m_path)); - } - - const string& m_path; - const Schema& m_schema; - bp::object result; - }; - - bp::object getOptions(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - ConvertOptions convertOptions(path, schema); - templatize(schema.getValueType(path), convertOptions); - return convertOptions.result; - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getOptions' should be a string"); - } - - - bp::object getAllowedStates(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const std::string s = karabo::util::toString(schema.getAllowedStates(path)); - const vector v = karabo::util::fromString(s); - // now construct python states - bp::list states; - bp::object sModule = bp::import("karabo.common.states"); - for (vector::const_iterator it = v.begin(); it != v.end(); ++it) { - states.append(sModule.attr("State")(*it)); - } - - return states; - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAllowedStates' should be a string"); - } - - //************************************************************* - // Wrapper functions for : setDefaultValue, getDefaultValue, getDefaultValueAs * - //************************************************************* - - - void setDefaultValue(Schema& self, const bp::object& obj, const bp::object& value) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - boost::any any; - karathon::Wrapper::toAny(value, any); - self.setDefaultValue(path, any); - } else - throw KARABO_PYTHON_EXCEPTION( - "Python argument defining the key name in 'setDefaultValue' should be a string"); - } - - - bp::object getDefaultValue(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_DEFAULT_VALUE), false); - } - throw KARABO_PYTHON_EXCEPTION("Python argument defining the key name in 'getDefaultValue' should be a string"); - } - - - bp::object getDefaultValueAs(const Schema& schema, const bp::object& obj, - const karathon::PyTypes::ReferenceType& pytype) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - - switch (pytype) { - case karathon::PyTypes::BOOL: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::INT32: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::UINT32: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::INT64: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::UINT64: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::STRING: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::FLOAT: - return bp::object(schema.getDefaultValueAs(path)); - case karathon::PyTypes::DOUBLE: - return bp::object(schema.getDefaultValueAs(path)); - case Types::VECTOR_BOOL: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - case Types::VECTOR_INT32: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - case Types::VECTOR_UINT32: - return karathon::Wrapper::fromStdVectorToPyArray( - schema.getDefaultValueAs(path)); - case Types::VECTOR_INT64: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - case Types::VECTOR_UINT64: - return karathon::Wrapper::fromStdVectorToPyArray( - schema.getDefaultValueAs(path)); - case Types::VECTOR_STRING: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - case Types::VECTOR_FLOAT: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - case Types::VECTOR_DOUBLE: - return karathon::Wrapper::fromStdVectorToPyArray(schema.getDefaultValueAs(path)); - default: - break; - } - throw KARABO_NOT_SUPPORTED_EXCEPTION("Type is not supported"); - } - throw KARABO_PYTHON_EXCEPTION( - "Python first argument in 'getDefaultValueAs' should be a string (defining a key name)"); - } - - //************************************************************************ - // Wrapper functions for : aliasHasKey, getAliasFromKey, getKeyFromAlias * - //************************************************************************ - - - bool aliasHasKey(const Schema& schema, const bp::object& obj) { - if (PyLong_Check(obj.ptr())) { - int param = bp::extract(obj); - return schema.aliasHasKey(param); - } else if (PyUnicode_Check(obj.ptr())) { - std::string param = bp::extract(obj); - return schema.aliasHasKey(param); - } else if (PyFloat_Check(obj.ptr())) { - double param = bp::extract(obj); - return schema.aliasHasKey(param); - } else if (PyList_Check(obj.ptr())) { - bp::ssize_t size = bp::len(obj); - if (size == 0) { - std::vector params = std::vector(); - return schema.aliasHasKey(params); - } - bp::object list0 = obj[0]; - if (list0.ptr() == Py_None) { - std::vector v; - for (bp::ssize_t i = 0; i < size; ++i) v.push_back(CppNone()); - return schema.aliasHasKey(v); - } - if (PyBool_Check(list0.ptr())) { - std::vector v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.aliasHasKey(v); - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.aliasHasKey(v); - } - if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.aliasHasKey(v); - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.aliasHasKey(v); - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.aliasHasKey(v); - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - bp::object str(bp::handle<>(PyUnicode_AsUTF8String(static_cast(obj[i]).ptr()))); - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(str.ptr(), &size); - v[i] = string(data, size); - } - return schema.aliasHasKey(v); - } - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'aliasHasKey': type is not supported"); - } - - - bp::object getAliasFromKey(const Schema& schema, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - string path = bp::extract(obj); - const Hash& h = schema.getParameterHash(); - return karathon::Wrapper::toObject(h.getAttributeAsAny(path, KARABO_SCHEMA_ALIAS), false); - } else { - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getAliasFromKey' should be a string"); - } - } - - - string getKeyFromAlias(const Schema& schema, const bp::object& obj) { - if (PyLong_Check(obj.ptr())) { - int param = bp::extract(obj); - return schema.getKeyFromAlias(param); - } else if (PyUnicode_Check(obj.ptr())) { - std::string param = bp::extract(obj); - return schema.getKeyFromAlias(param); - } else if (PyFloat_Check(obj.ptr())) { - double param = bp::extract(obj); - return schema.getKeyFromAlias(param); - } else if (PyList_Check(obj.ptr())) { - bp::ssize_t size = bp::len(obj); - if (size == 0) { - std::vector params = std::vector(); - return schema.getKeyFromAlias(params); - } - bp::object list0 = obj[0]; - if (list0.ptr() == Py_None) { - std::vector v; - for (bp::ssize_t i = 0; i < size; ++i) v.push_back(CppNone()); - return schema.getKeyFromAlias(v); - } - if (PyBool_Check(list0.ptr())) { - std::vector v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.getKeyFromAlias(v); - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.getKeyFromAlias(v); - } - if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.getKeyFromAlias(v); - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.getKeyFromAlias(v); - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return schema.getKeyFromAlias(v); - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - bp::object str(bp::handle<>(PyUnicode_AsUTF8String(static_cast(obj[i]).ptr()))); - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(str.ptr(), &size); - v[i] = string(data, size); - } - return schema.getKeyFromAlias(v); - } - } - throw KARABO_PYTHON_EXCEPTION("Python argument in 'getKeyFromAlias': type is not supported"); - } - - - void help(Schema& schema, const std::string& classId = "") { - schema.help(classId); - } - - - bp::object merge(Schema& schema, const Schema& schema2) { - schema.merge(schema2); - return bp::object(schema); - } - - - bp::object copy(Schema& schema, const Schema& schema2) { - schema = schema2; - return bp::object(schema); - } - - - void updateAliasMap(Schema& schema) { - schema.updateAliasMap(); - } - - - const std::string getInfoForAlarm(Schema& schema, const std::string& path, const bp::object condition) { - const std::string className = bp::extract(condition.attr("__class__").attr("__name__")); - if (className != "AlarmCondition") { - throw KARABO_PYTHON_EXCEPTION("Python argument for condition needs to be of type AlarmCondition and not " + - className); - } - const std::string conditionName = bp::extract(condition.attr("value")); - return schema.getInfoForAlarm(path, karabo::util::AlarmCondition::fromString(conditionName)); - } - - const bool doesAlarmNeedAcknowledging(Schema& schema, const std::string& path, const bp::object condition) { - const std::string className = bp::extract(condition.attr("__class__").attr("__name__")); - if (className != "AlarmCondition") { - throw KARABO_PYTHON_EXCEPTION("Python argument for condition needs to be of type AlarmCondition and not " + - className); - } - const std::string conditionName = bp::extract(condition.attr("value")); - return schema.doesAlarmNeedAcknowledging(path, karabo::util::AlarmCondition::fromString(conditionName)); - } - - - void setAllowedStates(Schema& self, const std::string& path, PyObject* rargs) { - bp::tuple args = bp::extract(rargs); - std::vector states; - for (unsigned int i = 0; i < bp::len(args); ++i) { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } - return self.setAllowedStates(path, states); - } - - - bp::object getAllowedActions(const Schema& self, const std::string& path) { - const std::vector& actions = self.getAllowedActions(path); - return karathon::Wrapper::fromStdVectorToPyList(actions); - } - - - void setAllowedActions(Schema& self, const std::string& path, const bp::object& actions) { - // Accept any Python iterable that provides strings - self.setAllowedActions(path, karathon::Wrapper::fromPyIterableToCppContainer(actions)); - } - - - bp::str assemblyRulesToStr(const Schema::AssemblyRules& self) { - std::ostringstream oss; - oss << "AssemblyRules(mode: " << self.m_accessMode << ", level: " << self.m_accessLevel << ", state: '" - << self.m_state << "')"; - return bp::str(oss.str()); - } -} // namespace schemawrap - - -namespace ndarrayelementwrap { - - - NDArrayElement& setAllowedActions(NDArrayElement& self, const bp::object& actions) { - // Accept any Python iterable that provides strings - return self.setAllowedActions(karathon::Wrapper::fromPyIterableToCppContainer(actions)); - } -} // namespace ndarrayelementwrap - - -struct HashFilterWrap { - static boost::shared_ptr byTag(const Schema& schema, const Hash& config, const std::string& tags, - const std::string& sep = ",") { - boost::shared_ptr result(new Hash); - HashFilter::byTag(schema, config, *result, tags, sep); - return result; - } - - - static boost::shared_ptr byAccessMode(const Schema& schema, const Hash& config, const AccessType& value) { - boost::shared_ptr result(new Hash); - HashFilter::byAccessMode(schema, config, *result, value); - return result; - } -}; - - -void exportPyUtilSchema() { - bp::enum_("AccessType").value("INIT", INIT).value("READ", READ).value("WRITE", WRITE).export_values(); - - bp::enum_("DaqDataType") - .value("PULSE", DaqDataType::PULSE) - .value("TRAIN", DaqDataType::TRAIN) - .value("PULSEMASTER", DaqDataType::PULSEMASTER) - .value("TRAINMASTER", DaqDataType::TRAINMASTER); - - bp::enum_("DAQPolicy") - .value("UNSPECIFIED", DAQPolicy::UNSPECIFIED) - .value("OMIT", DAQPolicy::OMIT) - .value("SAVE", DAQPolicy::SAVE); - - { - bp::enum_("MetricPrefix") - .value("YOTTA", MetricPrefix::YOTTA) - .value("ZETTA", MetricPrefix::ZETTA) - .value("EXA", MetricPrefix::EXA) - .value("PETA", MetricPrefix::PETA) - .value("TERA", MetricPrefix::TERA) - .value("GIGA", MetricPrefix::GIGA) - .value("MEGA", MetricPrefix::MEGA) - .value("KILO", MetricPrefix::KILO) - .value("HECTO", MetricPrefix::HECTO) - .value("DECA", MetricPrefix::DECA) - .value("NONE", MetricPrefix::NONE) - .value("DECI", MetricPrefix::DECI) - .value("CENTI", MetricPrefix::CENTI) - .value("MILLI", MetricPrefix::MILLI) - .value("MICRO", MetricPrefix::MICRO) - .value("NANO", MetricPrefix::NANO) - .value("PICO", MetricPrefix::PICO) - .value("FEMTO", MetricPrefix::FEMTO) - .value("ATTO", MetricPrefix::ATTO) - .value("ZEPTO", MetricPrefix::ZEPTO) - .value("YOCTO", MetricPrefix::YOCTO) - .export_values(); - bp::enum_("Unit") - .value("NUMBER", Unit::NUMBER) - .value("COUNT", Unit::COUNT) - .value("METER", Unit::METER) - .value("GRAM", Unit::GRAM) - .value("SECOND", Unit::SECOND) - .value("AMPERE", Unit::AMPERE) - .value("KELVIN", Unit::KELVIN) - .value("MOLE", Unit::MOLE) - .value("CANDELA", Unit::CANDELA) - .value("HERTZ", Unit::HERTZ) - .value("RADIAN", Unit::RADIAN) - .value("DEGREE", Unit::DEGREE) - .value("STERADIAN", Unit::STERADIAN) - .value("NEWTON", Unit::NEWTON) - .value("PASCAL", Unit::PASCAL) - .value("JOULE", Unit::JOULE) - .value("ELECTRONVOLT", Unit::ELECTRONVOLT) - .value("WATT", Unit::WATT) - .value("COULOMB", Unit::COULOMB) - .value("VOLT", Unit::VOLT) - .value("FARAD", Unit::FARAD) - .value("OHM", Unit::OHM) - .value("SIEMENS", Unit::SIEMENS) - .value("WEBER", Unit::WEBER) - .value("TESLA", Unit::TESLA) - .value("HENRY", Unit::HENRY) - .value("DEGREE_CELSIUS", Unit::DEGREE_CELSIUS) - .value("LUMEN", Unit::LUMEN) - .value("LUX", Unit::LUX) - .value("BECQUEREL", Unit::BECQUEREL) - .value("GRAY", Unit::GRAY) - .value("SIEVERT", Unit::SIEVERT) - .value("KATAL", Unit::KATAL) - .value("MINUTE", Unit::MINUTE) - .value("HOUR", Unit::HOUR) - .value("DAY", Unit::DAY) - .value("YEAR", Unit::YEAR) - .value("BAR", Unit::BAR) - .value("PIXEL", Unit::PIXEL) - .value("BYTE", Unit::BYTE) - .value("BIT", Unit::BIT) - .value("METER_PER_SECOND", Unit::METER_PER_SECOND) - .value("VOLT_PER_SECOND", Unit::VOLT_PER_SECOND) - .value("AMPERE_PER_SECOND", Unit::AMPERE_PER_SECOND) - .value("PERCENT", Unit::PERCENT) - .value("NOT_ASSIGNED", Unit::NOT_ASSIGNED) - .export_values(); - } - - { // Exposing std::vector - typedef bp::class_> VectorStringExposer; - VectorStringExposer exposerOfVectorString = VectorStringExposer("VectorString"); - bp::scope scopeOfVectorString(exposerOfVectorString); - exposerOfVectorString.def(bp::vector_indexing_suite, true>()); - } - - { // exposing ::Schema - - bp::class_> s("Schema"); - s.def(bp::init<>()); - s.def(bp::init>()); - - bp::enum_("AssignmentType") - .value("OPTIONAL", Schema::OPTIONAL_PARAM) - .value("MANDATORY", Schema::MANDATORY_PARAM) - .value("INTERNAL", Schema::INTERNAL_PARAM) - .export_values(); - bp::enum_("AccessLevel") - .value("OBSERVER", Schema::OBSERVER) - .value("USER", Schema::USER) - .value("OPERATOR", Schema::OPERATOR) - .value("EXPERT", Schema::EXPERT) - .value("ADMIN", Schema::ADMIN) - .export_values(); - bp::enum_("LeafType") - .value("PROPERTY", Schema::PROPERTY) - .value("COMMAND", Schema::COMMAND) - .value("STATE", Schema::STATE) - .value("ALARM_CONDITION", Schema::ALARM_CONDITION) - .export_values(); - bp::enum_("NodeType") - .value("LEAF", Schema::LEAF) - .value("NODE", Schema::NODE) - .value("CHOICE_OF_NODES", Schema::CHOICE_OF_NODES) - .value("LIST_OF_NODES", Schema::LIST_OF_NODES) - .export_values(); - bp::enum_("ArchivePolicy") - .value("EVERY_EVENT", Schema::EVERY_EVENT) - .value("EVERY_100MS", Schema::EVERY_100MS) - .value("EVERY_1S", Schema::EVERY_1S) - .value("EVERY_5S", Schema::EVERY_5S) - .value("EVERY_10S", Schema::EVERY_10S) - .value("EVERY_1MIN", Schema::EVERY_1MIN) - .value("EVERY_10MIN", Schema::EVERY_10MIN) - .value("NO_ARCHIVING", Schema::NO_ARCHIVING) - .export_values(); - bp::class_("AssemblyRules", - bp::init>( - (bp::arg("accessMode") = operator|(INIT, WRITE), bp::arg("state") = "", - bp::arg("accessLevel") = -1))) - .def_readwrite("m_accessMode", &Schema::AssemblyRules::m_accessMode) - .def_readwrite("m_accessLevel", &Schema::AssemblyRules::m_accessLevel) - .def_readwrite("m_state", &Schema::AssemblyRules::m_state) - .def("__str__", &schemawrap::assemblyRulesToStr); - - s.def(bp::self_ns::str(bp::self)); - - - //********* General functions on Schema ******* - - s.def("has", (bool(Schema::*)(string const&) const)(&Schema::has), bp::arg("path")); - - s.def("__contains__", (bool(Schema::*)(string const&) const)(&Schema::has), bp::arg("path")); - - s.def("empty", (bool(Schema::*)() const)(&Schema::empty)); - - s.def("merge", (void(Schema::*)(Schema const&))(&Schema::merge), bp::arg("schema")); - - s.def("__iadd__", &schemawrap::merge, bp::arg("schema")); - - s.def("copy", &schemawrap::copy, bp::arg("schema")); - - //********* 'get'-methods ********************* - s.def("getRequiredAccessLevel", &Schema::getRequiredAccessLevel); - - s.def("getParameterHash", &schemawrap::getParameterHash); - - s.def("getAccessMode", &Schema::getAccessMode); - - s.def("getAssemblyRules", &Schema::getAssemblyRules); - - s.def("getAssignment", &Schema::getAssignment); - - s.def("getSkipValidation", &Schema::getSkipValidation); - - s.def("getDescription", &Schema::getDescription, bp::return_value_policy()); - - s.def("getDisplayType", &Schema::getDisplayType, bp::return_value_policy()); - - s.def("getDisplayedName", &Schema::getDisplayedName, bp::return_value_policy()); - - s.def("getUnit", (const int (Schema::*)(const std::string& path) const) & Schema::getUnit, (bp::arg("path"))); - - s.def("getUnitName", &Schema::getUnitName, bp::return_value_policy()); - - s.def("getUnitSymbol", &Schema::getUnitSymbol, bp::return_value_policy()); - - s.def("getMetricPrefix", &Schema::getMetricPrefix); - - s.def("getMetricPrefixName", &Schema::getMetricPrefixName, bp::return_value_policy()); - - s.def("getMetricPrefixSymbol", &Schema::getMetricPrefixSymbol, - bp::return_value_policy()); - - s.def("getRootName", &Schema::getRootName, bp::return_value_policy()); - - s.def("getValueType", &schemawrap::getValueType, (bp::arg("path"))); - - s.def("getNodeType", &Schema::getNodeType); - - s.def("getMinInc", &schemawrap::getMinInc, (bp::arg("path"))); - - s.def("getMaxInc", &schemawrap::getMaxInc); - - s.def("getMinExc", &schemawrap::getMinExc); - - s.def("getMaxExc", &schemawrap::getMaxExc); - - s.def("getMinIncAs", &schemawrap::getMinIncAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getMaxIncAs", &schemawrap::getMaxIncAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getMinExcAs", &schemawrap::getMinExcAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getMaxExcAs", &schemawrap::getMaxExcAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getAliasAsString", &Schema::getAliasAsString); - - s.def("getKeys", &schemawrap::getKeys, (bp::arg("path") = "")); - - s.def("getPaths", &schemawrap::getPaths); - - s.def("getOptions", &schemawrap::getOptions); - - s.def("getTags", &schemawrap::getTags); - - s.def("getAllowedStates", &schemawrap::getAllowedStates); - - s.def("getDefaultValue", &schemawrap::getDefaultValue); - - s.def("getDefaultValueAs", &schemawrap::getDefaultValueAs); - - s.def("getMin", &Schema::getMin, bp::return_value_policy()); - - s.def("getMax", &Schema::getMax, bp::return_value_policy()); - - s.def("getMinSize", (const unsigned int& (Schema::*)(const string&) const)(&Schema::getMinSize), - bp::return_value_policy()); - - s.def("getMaxSize", (const unsigned int& (Schema::*)(const string&) const)(&Schema::getMaxSize), - bp::return_value_policy()); - - s.def("getArchivePolicy", &Schema::getArchivePolicy, bp::return_value_policy()); - - s.def("getWarnLow", &schemawrap::getWarnLow); - - s.def("getWarnHigh", &schemawrap::getWarnHigh); - - s.def("getAlarmLow", &schemawrap::getAlarmLow); - - s.def("getAlarmHigh", &schemawrap::getAlarmHigh); - - s.def("getWarnVarianceLow", &Schema::getWarnVarianceLow); - - s.def("getWarnVarianceHigh", &Schema::getWarnVarianceHigh); - - s.def("getAlarmVarianceLow", &Schema::getAlarmVarianceLow); - - s.def("getAlarmVarianceHigh", &Schema::getAlarmVarianceHigh); - - s.def("getWarnLowAs", &schemawrap::getWarnLowAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getWarnHighAs", &schemawrap::getWarnHighAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getAlarmLowAs", &schemawrap::getAlarmLowAs, (bp::arg("path"), bp::arg("pytype"))); - - s.def("getAlarmHighAs", &schemawrap::getAlarmHighAs, (bp::arg("path"), bp::arg("pytype"))); - - - //********* 'has'-methods **************** - - s.def("keyHasAlias", &Schema::keyHasAlias, (bp::arg("key"))); - - s.def("aliasHasKey", &schemawrap::aliasHasKey, (bp::arg("alias"))); - - s.def("getAliasFromKey", &schemawrap::getAliasFromKey, (bp::arg("key"))); - - s.def("getKeyFromAlias", &schemawrap::getKeyFromAlias, (bp::arg("alias"))); - - s.def("hasAccessMode", &Schema::hasAccessMode); - - s.def("hasAssignment", &Schema::hasAssignment); - - s.def("hasAllowedStates", &Schema::hasAllowedStates); - - s.def("hasDefaultValue", &Schema::hasDefaultValue); - - s.def("hasOptions", &Schema::hasOptions); - - s.def("hasTags", &Schema::hasTags); - - s.def("hasUnit", &Schema::hasUnit); - - s.def("hasMetricPrefix", &Schema::hasMetricPrefix); - - s.def("hasMinInc", &Schema::hasMinInc); - - s.def("hasMaxInc", &Schema::hasMaxInc); - - s.def("hasMinExc", &Schema::hasMinExc); - - s.def("hasMaxExc", &Schema::hasMaxExc); - - s.def("hasWarnLow", &Schema::hasWarnLow); - - s.def("hasWarnHigh", &Schema::hasWarnHigh); - - s.def("hasAlarmLow", &Schema::hasAlarmLow); - - s.def("hasAlarmHigh", &Schema::hasAlarmHigh); - - s.def("hasWarnVarianceLow", &Schema::hasWarnVarianceLow); - - s.def("hasWarnVarianceHigh", &Schema::hasWarnVarianceHigh); - - s.def("hasAlarmVarianceLow", &Schema::hasAlarmVarianceLow); - - s.def("hasAlarmVarianceHigh", &Schema::hasAlarmVarianceHigh); - - s.def("hasArchivePolicy", &Schema::hasArchivePolicy); - - s.def("hasDisplayedName", &Schema::hasDisplayedName); - - s.def("hasDisplayType", &Schema::hasDisplayType); - - s.def("hasDescription", &Schema::hasDescription); - - s.def("hasMin", &Schema::hasMin); - - s.def("hasMax", &Schema::hasMax); - - s.def("hasMinSize", &Schema::hasMinSize); - - s.def("hasMaxSize", &Schema::hasMaxSize); - - //********* 'is'-methods **************** - - s.def("isAccessInitOnly", &Schema::isAccessInitOnly); - s.def("isAccessReadOnly", &Schema::isAccessReadOnly); - s.def("isAccessReconfigurable", &Schema::isAccessReconfigurable); - - s.def("isAssignmentInternal", &Schema::isAssignmentInternal); - s.def("isAssignmentMandatory", &Schema::isAssignmentMandatory); - s.def("isAssignmentOptional", &Schema::isAssignmentOptional); - - s.def("isChoiceOfNodes", &Schema::isChoiceOfNodes); - s.def("isListOfNodes", &Schema::isListOfNodes); - s.def("isLeaf", &Schema::isLeaf); - s.def("isNode", &Schema::isNode); - s.def("isCommand", &Schema::isCommand); - s.def("isProperty", &Schema::isProperty); - - //********* Help function to show all parameters ******* - s.def("help", &schemawrap::help, (bp::arg("classId") = "")); - - s.def("applyRuntimeUpdates", &Schema::applyRuntimeUpdates, bp::arg("updates")); - - s.def("getClassInfo", (ClassInfo(Schema::*)() const)(&Schema::getClassInfo), - (ClassInfo(SchemaWrapper::*)() const)(&SchemaWrapper::default_getClassInfo)); - - s.def("classInfo", (ClassInfo(*)())(&Schema::classInfo)).staticmethod("classInfo"); - - s.def("setAssemblyRules", (void(Schema::*)(const Schema::AssemblyRules&)) & Schema::setAssemblyRules, - (bp::arg("rules"))); - s.def("setAccessMode", &Schema::setAccessMode, (bp::arg("path"), bp::arg("value"))); - s.def("setDisplayedName", &Schema::setDisplayedName, (bp::arg("path"), bp::arg("value"))); - s.def("setDescription", &Schema::setDescription, (bp::arg("path"), bp::arg("value"))); - s.def("setTags", &Schema::setTags, (bp::arg("path"), bp::arg("value"), bp::arg("sep") = ",;")); - s.def("setDisplayType", &Schema::setDisplayType, (bp::arg("path"), bp::arg("value"))); - s.def("setAssignment", &Schema::setAssignment, (bp::arg("path"), bp::arg("value"))); - s.def("setSkipValidation", &Schema::setSkipValidation, (bp::arg("path"), bp::arg("value"))); - s.def("setOptions", &Schema::setOptions, (bp::arg("path"), bp::arg("value"), bp::arg("sep") = ",;")); - s.def("setAllowedStates", &schemawrap::setAllowedStates, (bp::arg("path"), bp::arg("value"))); - s.def("setDefaultValue", &schemawrap::setDefaultValue, (bp::arg("path"), bp::arg("value"))); - s.def("setAlias", &schemawrap::setAlias, (bp::arg("path"), bp::arg("value"))); // setAlias - s.def("setUnit", &Schema::setUnit, (bp::arg("path"), bp::arg("value"))); - s.def("setMetricPrefix", &Schema::setMetricPrefix, (bp::arg("path"), bp::arg("value"))); - s.def("setMinInc", &schemawrap::setMinInc, (bp::arg("path"), bp::arg("value"))); - s.def("setMaxInc", &schemawrap::setMaxInc, (bp::arg("path"), bp::arg("value"))); - s.def("setMinExc", &schemawrap::setMinExc, (bp::arg("path"), bp::arg("value"))); - s.def("setMaxExc", &schemawrap::setMaxExc, (bp::arg("path"), bp::arg("value"))); - s.def("setMinSize", &Schema::setMinSize, (bp::arg("path"), bp::arg("value"))); - s.def("setMaxSize", &Schema::setMaxSize, (bp::arg("path"), bp::arg("value"))); - s.def("setWarnLow", &schemawrap::setWarnLow, (bp::arg("path"), bp::arg("value"))); - s.def("setWarnHigh", &schemawrap::setWarnHigh, (bp::arg("path"), bp::arg("value"))); - s.def("setAlarmLow", &schemawrap::setAlarmLow, (bp::arg("path"), bp::arg("value"))); - s.def("setAlarmHigh", &schemawrap::setAlarmHigh, (bp::arg("path"), bp::arg("value"))); - s.def("setWarnVarianceLow", &Schema::setWarnVarianceLow, (bp::arg("path"), bp::arg("value"))); - s.def("setWarnVarianceHigh", &Schema::setWarnVarianceHigh, (bp::arg("path"), bp::arg("value"))); - s.def("setAlarmVarianceLow", &Schema::setAlarmVarianceLow, (bp::arg("path"), bp::arg("value"))); - s.def("setAlarmVarianceHigh", &Schema::setAlarmVarianceHigh, (bp::arg("path"), bp::arg("value"))); - s.def("getRollingStatsEvalInterval", &Schema::getRollingStatsEvalInterval, (bp::arg("path"), bp::arg("value"))); - s.def("getInfoForAlarm", &schemawrap::getInfoForAlarm, (bp::arg("path"), bp::arg("condition"))); - s.def("doesAlarmNeedAcknowledging", &schemawrap::doesAlarmNeedAcknowledging, - (bp::arg("path"), bp::arg("condition"))); - s.def("setArchivePolicy", &Schema::setArchivePolicy, (bp::arg("path"), bp::arg("value"))); - s.def("setMin", &Schema::setMin, (bp::arg("path"), bp::arg("value"))); - s.def("setMax", &Schema::setMax, (bp::arg("path"), bp::arg("value"))); - s.def("setRequiredAccessLevel", &Schema::setRequiredAccessLevel, (bp::arg("path"), bp::arg("value"))); - // s.def("", &Schema::, ()); // overwrite<>(default) not implemented - s.def("updateAliasMap", &schemawrap::updateAliasMap); - s.def("hasRollingStatistics", &Schema::hasRollingStatistics); - s.def("subSchema", &Schema::subSchema, (bp::arg("subNodePath"), bp::arg("filterTags") = "")); - s.def("subSchemaByRules", &Schema::subSchemaByRules, (bp::arg("assemblyRules"))); - s.def("setDaqDataType", &Schema::setDaqDataType, (bp::arg("path"), bp::arg("dataType"))); - s.def("getDaqDataType", &Schema::getDaqDataType, (bp::arg("path"))); - s.def("hasDaqDataType", &Schema::hasDaqDataType, (bp::arg("path"))); - s.def("setDAQPolicy", &Schema::setDAQPolicy, (bp::arg("path"), bp::arg("policy"))); - s.def("getDAQPolicy", &Schema::getDAQPolicy, (bp::arg("path"))); - s.def("hasDAQPolicy", &Schema::hasDAQPolicy, (bp::arg("path"))); - s.def("setDefaultDAQPolicy", &Schema::setDefaultDAQPolicy, (bp::arg("policy"))); - s.def("isCustomNode", &Schema::isCustomNode, (bp::arg("path"))); - s.def("getCustomNodeClass", &Schema::getCustomNodeClass, (bp::arg("path")), - bp::return_value_policy()); - s.def("hasAllowedActions", &Schema::hasAllowedActions, (bp::arg("path")), - "Check if element given by argument has allowed actions."); - s.def("getAllowedActions", &schemawrap::getAllowedActions, (bp::arg("path")), - "Return allowed actions of element given by argument."); - s.def("setAllowedActions", &schemawrap::setAllowedActions, (bp::arg("path"), bp::arg("actions")), - "Specify one or more actions that are allowed on the element.\n" - "If a Karabo device specifies allowed actions, that means that it offers\n" - "a specific slot interface to operate on this element.\n" - "Which allowed actions require which interface is defined elsewhere."); - } // end Schema - - ///////////////////////////////////////////////////////////// - // DefaultValue, EType >, where EType: - // INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - // and DefaultValue - // and DefaultValue - - - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, int, INT32) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, unsigned int, UINT32) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, long long, INT64) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, unsigned long long, UINT64) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, float, FLOAT) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, double, DOUBLE) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, string, STRING) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(SimpleElement, bool, BOOL) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(PathElement, string, PATH) - KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(ByteArrayElement, ByteArray, BYTEARRAY) - - /////////////////////////////////////////////////////////////// - // AlarmSpecific, EType >, where EType: - // INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, int, ReadOnlySpecific, INT32) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, unsigned int, ReadOnlySpecific, UINT32) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, long long, ReadOnlySpecific, INT64) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, unsigned long long, ReadOnlySpecific, UINT64) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, float, ReadOnlySpecific, FLOAT) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, double, ReadOnlySpecific, DOUBLE) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, std::string, ReadOnlySpecific, STRING) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, bool, ReadOnlySpecific, BOOL) - - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, int, RollingStatsSpecific, INT32) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, unsigned int, RollingStatsSpecific, UINT32) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, long long, RollingStatsSpecific, INT64) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, unsigned long long, RollingStatsSpecific, - UINT64) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, float, RollingStatsSpecific, FLOAT) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, double, RollingStatsSpecific, DOUBLE) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, std::string, RollingStatsSpecific, STRING) - KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(SimpleElement, bool, RollingStatsSpecific, BOOL) - - /////////////////////////////////////////////////////////////// - // RollingStatSpecific, EType >, where EType: - // INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, int, INT32) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, unsigned int, UINT32) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, long long, INT64) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, unsigned long long, UINT64) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, float, FLOAT) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, double, DOUBLE) - KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(SimpleElement, bool, BOOL) - - /////////////////////////////////////////////////////////////// - // ReadOnlySpecific, EType >, where EType: - // INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - // and ReadOnlySpecific - // and ReadOnlySpecific - - - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, int, INT32) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, unsigned int, UINT32) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, long long, INT64) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, unsigned long long, UINT64) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, float, FLOAT) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, double, DOUBLE) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, std::string, STRING) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(SimpleElement, bool, BOOL) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(PathElement, std::string, PATH) - KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(ByteArrayElement, ByteArray, BYTEARRAY) - - - // ///////////////////////////////////////////////////////////// - // //DefaultValue, EType >, where EType: - // //INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - // //and DefaultValue - // - // KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(BitsetElement, unsigned char, BITSET8) - // KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(BitsetElement, unsigned short, BITSET16) - // KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(BitsetElement, unsigned int, BITSET32) - // KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(BitsetElement, unsigned long long, BITSET64) - // - // /////////////////////////////////////////////////////////////// - // //ReadOnlySpecific, EType >, where EType: - // //INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - // // and ReadOnlySpecific - // - // KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(BitsetElement, unsigned char, BITSET8) - // KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(BitsetElement, unsigned short, BITSET16) - // KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(BitsetElement, unsigned int, BITSET32) - // KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(BitsetElement, unsigned long long, BITSET64) - - /////////////////////////////////////////////////////////// - // DefaultValue, std::vector< EType > > where EType: - // BOOL, INT32, UINT32, INT64, UINT64, DOUBLE, STRING - - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(int, INT32) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(unsigned int, UINT32) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(long long, INT64) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(unsigned long long, UINT64) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(float, FLOAT) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(double, DOUBLE) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(std::string, STRING) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(bool, BOOL) - KARABO_PYTHON_VECTOR_DEFAULT_VALUE(char, CHAR) - - /////////////////////////////////////////////////////////////// - // ReadOnlySpecific, EType >, where EType: - // INT32, UINT32, INT64, UINT64, DOUBLE, STRING, BOOL - - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(int, INT32) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(unsigned int, UINT32) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(long long, INT64) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(unsigned long long, UINT64) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(float, FLOAT) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(double, DOUBLE) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(std::string, STRING) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(bool, BOOL) - KARABO_PYTHON_VECTOR_READONLYSPECIFIC(char, CHAR) - - - ////////////////////////////////////////////////////////////////////// - // Binding SimpleElement< EType >, where EType: - // int, long long, double, string, bool - // In Python: INT32_ELEMENT, UINT32_ELEMENT, INT64_ELEMENT, UINT64_ELEMENT, DOUBLE_ELEMENT, - // STRING_ELEMENT, BOOL_ELEMENT - - KARABO_PYTHON_SIMPLE(int, INT32) - KARABO_PYTHON_SIMPLE(unsigned int, UINT32) - KARABO_PYTHON_SIMPLE(long long, INT64) - KARABO_PYTHON_SIMPLE(unsigned long long, UINT64) - KARABO_PYTHON_SIMPLE(float, FLOAT) - KARABO_PYTHON_SIMPLE(double, DOUBLE) - KARABO_PYTHON_SIMPLE(string, STRING) - KARABO_PYTHON_SIMPLE(bool, BOOL) - - ////////////////////////////////////////////////////////////////////// - // Binding ByteArrayElement - // In Python : BYTE_ARRAY - { - bp::implicitly_convertible(); - bp::class_("BYTEARRAY_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_COMMON_ATTRIBUTES(ByteArrayElement); - } - - ////////////////////////////////////////////////////////////////////// - // Binding PathElement - // In Python : PATH_ELEMENT - { - bp::implicitly_convertible(); - typedef std::string EType; - bp::class_("PATH_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_COMMON_ATTRIBUTES(PathElement) KARABO_PYTHON_OPTIONS_NONVECTOR(PathElement) - .def("isInputFile", &PathElement::isInputFile, bp::return_internal_reference<>()) - .def("isOutputFile", &PathElement::isOutputFile, bp::return_internal_reference<>()) - .def("isDirectory", &PathElement::isDirectory, bp::return_internal_reference<>()); - } - - ////////////////////////////////////////////////////////////////////// - // Binding VectorElement< EType, std::vector > - // In Python : VECTOR_INT32_ELEMENT, VECTOR_UINT32_ELEMENT, - // VECTOR_INT64_ELEMENT, VECTOR_UINT64_ELEMENT, VECTOR_DOUBLE_ELEMENT, - // VECTOR_STRING_ELEMENT, VECTOR_BOOL_ELEMENT, VECTOR_CHAR_ELEMENT - - - KARABO_PYTHON_VECTOR(int, INT32) - KARABO_PYTHON_VECTOR(unsigned int, UINT32) - KARABO_PYTHON_VECTOR(long long, INT64) - KARABO_PYTHON_VECTOR(unsigned long long, UINT64) - KARABO_PYTHON_VECTOR(float, FLOAT) - KARABO_PYTHON_VECTOR(double, DOUBLE) - KARABO_PYTHON_VECTOR(string, STRING) - KARABO_PYTHON_VECTOR(bool, BOOL) - KARABO_PYTHON_VECTOR(char, CHAR) - - ////////////////////////////////////////////////////////////////////// - // Binding NDArrayElement - // In Python : NDARRAY_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("NDARRAY_ELEMENT", bp::init((bp::arg("expected")))) - .def("dtype", &NDArrayElementWrap::dtype, bp::arg("type"), bp::return_internal_reference<>()) - .def("shape", &NDArrayElementWrap::shape, bp::arg("shape"), bp::return_internal_reference<>()) - .def("unit", &NDArrayElement::unit, bp::return_internal_reference<>()) - .def("metricPrefix", &NDArrayElement::metricPrefix, bp::return_internal_reference<>()) - .def("observerAccess", &NDArrayElement::observerAccess, bp::return_internal_reference<>()) - .def("userAccess", &NDArrayElement::userAccess, bp::return_internal_reference<>()) - .def("operatorAccess", &NDArrayElement::operatorAccess, bp::return_internal_reference<>()) - .def("expertAccess", &NDArrayElement::expertAccess, bp::return_internal_reference<>()) - .def("adminAccess", &NDArrayElement::adminAccess, bp::return_internal_reference<>()) - .def("description", &NDArrayElement::description, bp::return_internal_reference<>()) - .def("displayedName", &NDArrayElement::displayedName, bp::return_internal_reference<>()) - .def("init", &NDArrayElement::init, bp::return_internal_reference<>()) - .def("key", &NDArrayElement::key, bp::return_internal_reference<>()) - .def("readOnly", &NDArrayElement::readOnly, bp::return_internal_reference<>()) - .def("reconfigurable", &NDArrayElement::reconfigurable, bp::return_internal_reference<>()) - .def("setAllowedActions", &ndarrayelementwrap::setAllowedActions, bp::arg("actions"), - "Specify one or more actions that are allowed on this node.\n" - "If a Karabo device specifies allowed actions for a node,\n" - "that means that it offers a specific slot interface to operate\n" - "on this node. Which allowed actions require which interface\n" - "is defined elsewhere", - bp::return_internal_reference<>()) - .def("skipValidation", &NDArrayElement::skipValidation, bp::return_internal_reference<>()) - .def("commit", &NDArrayElement::commit, bp::return_internal_reference<>()) - .def("commit", (NDArrayElement & (NDArrayElement::*)(karabo::util::Schema&))(&NDArrayElement::commit), - bp::arg("expected"), bp::return_internal_reference<>()); - } - - ////////////////////////////////////////////////////////////////////// - // Binding NodeElement - // In Python : NODE_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("NODE_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_NODE_CHOICE_LIST(NodeElement) - .def("appendParametersOf", &NodeElementWrap::appendParametersOf, (bp::arg("python_class")), - bp::return_internal_reference<>()) - .def("appendParametersOfConfigurableClass", &NodeElementWrap::appendParametersOfConfigurableClass, - (bp::arg("python_base_class"), bp::arg("classid")), bp::return_internal_reference<>()) - .def("appendSchema", &NodeElementWrap::appendSchema, (bp::arg("schema")), - bp::return_internal_reference<>()) - .def("setDaqDataType", &NodeElementWrap::setDaqDataType, (bp::arg("dataType")), - bp::return_internal_reference<>()) - .def("setSpecialDisplayType", &NodeElementWrap::setSpecialDisplayType, (bp::arg("displayType")), - bp::return_internal_reference<>()) - .def("setAllowedActions", &NodeElementWrap::setAllowedActions, (bp::arg("actions")), - bp::return_internal_reference<>(), - "Specify one or more actions that are allowed on this node.\n" - "If a Karabo device specifies allowed actions for a node,\n" - "that means that it offers a specific slot interface to operate\n" - "on this node. Which allowed actions require which interface\n" - "is defined elsewhere."); - } - - ////////////////////////////////////////////////////////////////////// - // Binding ListElement - // In Python : LIST_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("LIST_ELEMENT", - bp::init((bp::arg("expected")))) KARABO_PYTHON_NODE_CHOICE_LIST(ListElement) - .def("assignmentMandatory", &ListElement::assignmentMandatory, bp::return_internal_reference<>()) - .def("assignmentOptional", &ListElement::assignmentOptional, bp::return_internal_reference<>()) - .def("min", &ListElement::min, bp::return_internal_reference<>()) - .def("max", &ListElement::max, bp::return_internal_reference<>()) - .def("appendNodesOfConfigurationBase", &ListElementWrap::appendNodesOfConfigurationBase, - (bp::arg("python_base_class")), bp::return_internal_reference<>()) - .def("appendAsNode", &ListElementWrap::appendAsNode, (bp::arg("python_class"), bp::arg("nodeName") = ""), - bp::return_internal_reference<>()) - .def("init", &ListElement::init, bp::return_internal_reference<>()) - .def("reconfigurable", &ListElement::reconfigurable, bp::return_internal_reference<>()) - .def("setSpecialDisplayType", &ListElement::setSpecialDisplayType, bp::return_internal_reference<>()); - } - - { - typedef ReadOnlySpecific> ReadOnlySpec; - bp::class_("ReadOnlySpecificTABLE", bp::no_init) - .def("initialValue", &ReadOnlySpecificTableWrap::initialValueTable, (bp::arg("self"), bp::arg("pyList")), - bp::return_internal_reference<>()) - .def("defaultValue", &ReadOnlySpecificTableWrap::initialValueTable, (bp::arg("self"), bp::arg("pyList")), - bp::return_internal_reference<>()) - .def("archivePolicy", - (ReadOnlySpec & - (ReadOnlySpec::*)(karabo::util::Schema::ArchivePolicy const&))(&ReadOnlySpec::archivePolicy), - bp::return_internal_reference<>()) - .def("commit", (void(ReadOnlySpec::*)())(&ReadOnlySpec::commit)); - } - - - ////////////////////////////////////////////////////////////////////// - // Binding TableElement - // In Python : TABLE_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("TABLE_ELEMENT", bp::init((bp::arg("expected")))) - .def("observerAccess", &TableElement::observerAccess, bp::return_internal_reference<>()) - .def("userAccess", &TableElement::userAccess, bp::return_internal_reference<>()) - .def("operatorAccess", &TableElement::operatorAccess, bp::return_internal_reference<>()) - .def("expertAccess", &TableElement::expertAccess, bp::return_internal_reference<>()) - .def("adminAccess", &TableElement::adminAccess, bp::return_internal_reference<>()) - .def("allowedStates", bp::raw_function(&tableElementWrap::allowedStatesPy, 2)) - .def("assignmentInternal", &TableElement::assignmentInternal, bp::return_internal_reference<>()) - .def("assignmentMandatory", &TableElement::assignmentMandatory, bp::return_internal_reference<>()) - .def("assignmentOptional", &TableElement::assignmentOptional, bp::return_internal_reference<>()) - .def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()) - .def("commit", &TableElement::commit, bp::return_internal_reference<>()) - .def("commit", (TableElement & (TableElement::*)(karabo::util::Schema&))(&TableElement::commit), - bp::arg("expected"), bp::return_internal_reference<>()) - .def("description", &TableElement::description, bp::return_internal_reference<>()) - .def("displayedName", &TableElement::displayedName, bp::return_internal_reference<>()) - .def("init", &TableElement::init, bp::return_internal_reference<>()) - .def("key", &TableElement::key, bp::return_internal_reference<>()) - .def("reconfigurable", &TableElement::reconfigurable, bp::return_internal_reference<>()) - .def("tags", - (TableElement & (TableElement::*)(std::string const&, std::string const&))(&TableElement::tags), - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) - .def("tags", (TableElement & (TableElement::*)(std::vector const&))(&TableElement::tags), - (bp::arg("tags")), bp::return_internal_reference<>()) - .def("defaultValue", &DefaultValueTableWrap::defaultValue, (bp::arg("self"), bp::arg("pyList")), - bp::return_internal_reference<>()) - .def("noDefaultValue", - (TableElement & (karabo::util::TableDefaultValue::*)())( - &karabo::util::TableDefaultValue::noDefaultValue), - bp::return_internal_reference<>()) - .def("maxSize", (TableElement & (TableElement::*)(int const&))(&TableElement::maxSize), - bp::return_internal_reference<>()) - .def("minSize", (TableElement & (TableElement::*)(int const&))(&TableElement::minSize), - bp::return_internal_reference<>()) - .def("setNodeSchema", &TableElement::setColumns, (bp::arg("nodeSchema")), - bp::return_internal_reference<>(), "DEPRECATED - use 'setColumns' instead") - .def("setColumns", &TableElement::setColumns, (bp::arg("schema")), bp::return_internal_reference<>(), - "Set Schema describing the columns") - .def("readOnly", &TableElement::readOnly, bp::return_internal_reference<>()) - /*.def("addRow" - , (TableElement & (TableElement::*)(const Hash&))&TableElement::addRow, (bp::arg("nodeHash") = - Hash()) , bp::return_internal_reference<> ()) .def("addRow" , (TableElement & (TableElement::*)(const - Schema&, const Hash&))&TableElement::addRow, (bp::arg("nodeSchema"), bp::arg("nodeHash") = Hash()) , - bp::return_internal_reference<> ())*/ - ; - } - - /////////////////////////////////////////////////////////////////////////// - // TableDefaultValue - { - typedef TableDefaultValue DefTableElement; - bp::class_("DefaultValueTableElement", bp::no_init) - .def("defaultValue", &DefaultValueTableWrap::defaultValue, (bp::arg("self"), bp::arg("pyList")), - bp::return_internal_reference<>()) - .def("noDefaultValue", (TableElement & (DefTableElement::*)())(&DefTableElement::noDefaultValue), - bp::return_internal_reference<>()); - } - - ////////////////////////////////////////////////////////////////////// - // Binding ChoiceElement - // In Python : CHOICE_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("CHOICE_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_NODE_CHOICE_LIST(ChoiceElement) - .def("assignmentMandatory", &ChoiceElement::assignmentMandatory, bp::return_internal_reference<>()) - .def("assignmentOptional", &ChoiceElement::assignmentOptional, bp::return_internal_reference<>()) - .def("appendNodesOfConfigurationBase", &ChoiceElementWrap::appendNodesOfConfigurationBase, - (bp::arg("python_base_class")), bp::return_internal_reference<>()) - .def("appendAsNode", &ChoiceElementWrap::appendAsNode, - (bp::arg("python_class"), bp::arg("nodeName") = ""), bp::return_internal_reference<>()) - .def("reconfigurable", &ChoiceElement::reconfigurable, bp::return_internal_reference<>()) - .def("init", &ChoiceElement::init, bp::return_internal_reference<>()); - } - - ////////////////////////////////////////////////////////////////////// - // Binding InputElement - // In Python : INPUT_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("INPUT_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_NODE_CHOICE_LIST(InputElement) - .def("setInputType", &InputElementWrap::setInputType, (bp::arg("python_base_class")), - bp::return_internal_reference<>()); - } - - ////////////////////////////////////////////////////////////////////// - // Binding OutputElement - // In Python : OUTPUT_ELEMENT - { - bp::implicitly_convertible(); - bp::class_("OUTPUT_ELEMENT", bp::init((bp::arg("expected")))) - KARABO_PYTHON_NODE_CHOICE_LIST(OutputElement) - .def("setOutputType", &OutputElementWrap::setOutputType, (bp::arg("python_base_class")), - bp::return_internal_reference<>()); - } - - /////////////////////////////////////////////////////////////////////////// - // DefaultValue - { - typedef DefaultValue DefChoiceElement; - bp::class_("DefaultValueChoiceElement", bp::no_init) - .def("defaultValue", - (ChoiceElement & (DefChoiceElement::*)(string const&))(&DefChoiceElement::defaultValue), - (bp::arg("defValue")), bp::return_internal_reference<>()) - .def("defaultValueFromString", - (ChoiceElement & (DefChoiceElement::*)(string const&))(&DefChoiceElement::defaultValueFromString), - (bp::arg("defValue")), bp::return_internal_reference<>()) - .def("noDefaultValue", (ChoiceElement & (DefChoiceElement::*)())(&DefChoiceElement::noDefaultValue), - bp::return_internal_reference<>()); - } - - /////////////////////////////////////////////////////////////////////////// - // DefaultValue - { - typedef DefaultValue> DefListElement; - bp::class_("DefaultValueListElement", bp::no_init) - .def("defaultValue", &ListElementWrap::defaultValueList, (bp::arg("self"), bp::arg("pyList")), - bp::return_internal_reference<>()) - .def("defaultValueFromString", - (ListElement & (DefListElement::*)(string const&))(&DefListElement::defaultValueFromString), - (bp::arg("defValue")), bp::return_internal_reference<>()) - .def("noDefaultValue", (ListElement & (DefListElement::*)())(&DefListElement::noDefaultValue), - bp::return_internal_reference<>()); - } - - { - bp::class_("ValidatorValidationRules", bp::init<>()) - .def_readwrite("injectDefaults", &Validator::ValidationRules::injectDefaults) - .def_readwrite("allowUnrootedConfiguration", &Validator::ValidationRules::allowUnrootedConfiguration) - .def_readwrite("allowAdditionalKeys", &Validator::ValidationRules::allowAdditionalKeys) - .def_readwrite("allowMissingKeys", &Validator::ValidationRules::allowMissingKeys) - .def_readwrite("injectTimestamps", &Validator::ValidationRules::injectTimestamps) - .def_readwrite("forceInjectedTimestamp", &Validator::ValidationRules::forceInjectedTimestamp); - - bp::class_("Validator", bp::init<>()) - .def(bp::init()) - .def("validate", &ValidatorWrap::validate, - (bp::arg("schema"), bp::arg("configuration"), bp::arg("timestamp") = bp::object())) - .def("setValidationRules", &ValidatorWrap::setValidationRules, (bp::arg("rules"))) - .def("getValidationRules", &ValidatorWrap::getValidationRules) - .def("hasReconfigurableParameter", &ValidatorWrap::hasReconfigurableParameter) - .def("getRollingStatistics", &ValidatorWrap::getRollingStatistics, bp::arg("key"), - bp::return_internal_reference<>()); - } - - { - bp::implicitly_convertible(); - bp::class_("OVERWRITE_ELEMENT", bp::init((bp::arg("expected")))) - .def("key", (OverwriteElement & (OverwriteElement::*)(string const&))(&OverwriteElement::key), - (bp::arg("key")), bp::return_internal_reference<>()) - .def("setNewDisplayedName", - (OverwriteElement & (OverwriteElement::*)(string const&))(&OverwriteElement::setNewDisplayedName), - (bp::arg("name")), bp::return_internal_reference<>()) - .def("setNewDescription", - (OverwriteElement & (OverwriteElement::*)(string const&))(&OverwriteElement::setNewDescription), - (bp::arg("description")), bp::return_internal_reference<>()) - .def("setNewAlias", &OverwriteElementWrap().setNewAlias, (bp::arg("alias")), - bp::return_internal_reference<>()) - .def("setNewTags", &OverwriteElementWrap().setNewTags, (bp::arg("tags")), - bp::return_internal_reference<>(), "Overwrite tags, 'tags' can be a str or an iterable of str.") - .def("setNewAssignmentMandatory", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNewAssignmentMandatory), - bp::return_internal_reference<>()) - .def("setNewAssignmentOptional", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNewAssignmentOptional), - bp::return_internal_reference<>()) - .def("setNewAssignmentInternal", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNewAssignmentInternal), - bp::return_internal_reference<>()) - .def("setNowInit", (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowInit), - bp::return_internal_reference<>()) - .def("setNowReconfigurable", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowReconfigurable), - bp::return_internal_reference<>()) - .def("setNowReadOnly", (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowReadOnly), - bp::return_internal_reference<>()) - .def("setNowValidate", (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowValidate), - bp::return_internal_reference<>()) - .def("setNowSkipValidation", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowSkipValidation), - bp::return_internal_reference<>()) - .def("setNewDefaultValue", &OverwriteElementWrap().setNewDefaultValue, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMinInc", &OverwriteElementWrap().setNewMinInc, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMaxInc", &OverwriteElementWrap().setNewMaxInc, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMinExc", &OverwriteElementWrap().setNewMinExc, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMaxExc", &OverwriteElementWrap().setNewMaxExc, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMinSize", &OverwriteElementWrap().setNewMinSize, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewMaxSize", &OverwriteElementWrap().setNewMaxSize, (bp::arg("value")), - bp::return_internal_reference<>()) - .def("setNewOptions", bp::raw_function(&OverwriteElementWrap::setNewOptions, 2)) - .def("setNewAllowedStates", bp::raw_function(&OverwriteElementWrap::setNewAllowedStates, 2)) - .def("setNowObserverAccess", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowObserverAccess), - bp::return_internal_reference<>()) - .def("setNowUserAccess", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowUserAccess), - bp::return_internal_reference<>()) - .def("setNowOperatorAccess", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowOperatorAccess), - bp::return_internal_reference<>()) - .def("setNowExpertAccess", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowExpertAccess), - bp::return_internal_reference<>()) - .def("setNowAdminAccess", - (OverwriteElement & (OverwriteElement::*)())(&OverwriteElement::setNowAdminAccess), - bp::return_internal_reference<>()) - .def("setNewUnit", - (OverwriteElement & (OverwriteElement::*)(const UnitType&))(&OverwriteElement::setNewUnit), - (bp::arg("value")), bp::return_internal_reference<>()) - .def("setNewMetricPrefix", - (OverwriteElement & - (OverwriteElement::*)(const MetricPrefixType&))(&OverwriteElement::setNewMetricPrefix), - (bp::arg("value")), bp::return_internal_reference<>()) - .def("commit", (void(OverwriteElement::*)())(&OverwriteElement::commit)); - } - - { - bp::class_("HashFilter", bp::no_init) - .def("byTag", HashFilterWrap::byTag, - (bp::arg("schema"), bp::arg("config"), bp::arg("tags"), bp::arg("sep") = ",")) - .staticmethod("byTag") - .def("byAccessMode", HashFilterWrap::byAccessMode, - (bp::arg("schema"), bp::arg("config"), bp::arg("accessMode"))) - .staticmethod("byAccessMode"); - } -} // end exportPyUtilSchema diff --git a/src/karathon/PyUtilStateElement.cc b/src/karathon/PyUtilStateElement.cc deleted file mode 100644 index e5b3838597..0000000000 --- a/src/karathon/PyUtilStateElement.cc +++ /dev/null @@ -1,85 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -#include "PythonMacros.hh" -#include "boost/python.hpp" -#include "boost/python/raw_function.hpp" - - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -class StateElementWrap { - public: - static StateElement& initialValuePy(StateElement& self, const bp::object& value) { - const std::string className = bp::extract(value.attr("__class__").attr("__name__")); - if (className == "State") { - const std::string state = bp::extract(value.attr("name")); - return self.initialValue(karabo::util::State::fromString(state)); - } else { - throw KARABO_PYTHON_EXCEPTION("defaultValue expects parameter of type State."); - } - } - - static bp::object optionsPy(bp::tuple args, bp::dict kwargs) { - StateElement& self = bp::extract(args[0]); - std::vector states; - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string className = bp::extract(args[i].attr("__class__").attr("__name__")); - if (className == "State") { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } else { - throw KARABO_PYTHON_EXCEPTION("options() an arbitrary number of arguments of type State."); - } - } - self.options(states); - return args[0]; - } -}; - - -void exportPyUtilStateElement() { - bp::implicitly_convertible(); - bp::class_("STATE_ELEMENT", bp::init((bp::arg("expected")))) - .def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()) - .def("commit", &StateElement::commit, bp::return_internal_reference<>()) - .def("commit", (StateElement & (StateElement::*)(karabo::util::Schema&))(&StateElement::commit), - bp::arg("expected"), bp::return_internal_reference<>()) - .def("description", &StateElement::description, bp::return_internal_reference<>()) - .def("displayedName", &StateElement::displayedName, bp::return_internal_reference<>()) - .def("key", &StateElement::key, bp::return_internal_reference<>()) - .def("tags", (StateElement & (StateElement::*)(std::string const&, std::string const&))(&StateElement::tags), - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) - .def("tags", (StateElement & (StateElement::*)(std::vector const&))(&StateElement::tags), - (bp::arg("tags")), bp::return_internal_reference<>()) - .def("options", bp::raw_function(&StateElementWrap::optionsPy, 2)) - .def("daqPolicy", &StateElement::daqPolicy, bp::return_internal_reference<>()) - .def("defaultValue", &StateElementWrap::initialValuePy, (bp::arg("value")), bp::return_internal_reference<>()) - .def("initialValue", &StateElementWrap::initialValuePy, (bp::arg("value")), - bp::return_internal_reference<>()); -} diff --git a/src/karathon/PyUtilTimeDuration.cc b/src/karathon/PyUtilTimeDuration.cc deleted file mode 100644 index 647638cf54..0000000000 --- a/src/karathon/PyUtilTimeDuration.cc +++ /dev/null @@ -1,106 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include - -#include "boost/python.hpp" - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -void exportPyUtilTimeDuration() { - bp::class_ t("TimeDuration", bp::init<>()); - t.def(bp::init((bp::arg("hash")))); - bp::implicitly_convertible(); - t.def(bp::init((bp::arg("seconds"), bp::arg("fractions")))); - t.def(bp::init( - (bp::arg("days"), bp::arg("hours"), bp::arg("minutes"), bp::arg("seconds"), bp::arg("fractions")))); - t.def(bp::self_ns::str(bp::self)); - t.def("set", (TimeDuration & (TimeDuration::*)(TimeValue const, TimeValue const))(&TimeDuration::set), - (bp::arg("seconds"), bp::arg("fractions")), bp::return_internal_reference<>()); - - t.def("set", - (TimeDuration & - (TimeDuration::*)(int const, int const, int const, TimeValue const, TimeValue const))(&TimeDuration::set), - (bp::arg("days"), bp::arg("hours"), bp::arg("minutes"), bp::arg("seconds"), bp::arg("fractions")), - bp::return_internal_reference<>()); - - t.def("add", (TimeDuration & (TimeDuration::*)(TimeValue const, TimeValue const))(&TimeDuration::add), - (bp::arg("seconds"), bp::arg("fractions")), bp::return_internal_reference<>()); - - t.def("add", - (TimeDuration & - (TimeDuration::*)(int const, int const, int const, TimeValue const, TimeValue const))(&TimeDuration::add), - (bp::arg("days"), bp::arg("hours"), bp::arg("minutes"), bp::arg("seconds"), bp::arg("fractions")), - bp::return_internal_reference<>()); - - t.def("sub", (TimeDuration & (TimeDuration::*)(TimeValue const, TimeValue const))(&TimeDuration::sub), - (bp::arg("seconds"), bp::arg("fractions")), bp::return_internal_reference<>()); - - t.def("sub", - (TimeDuration & - (TimeDuration::*)(int const, int const, int const, TimeValue const, TimeValue const))(&TimeDuration::sub), - (bp::arg("days"), bp::arg("hours"), bp::arg("minutes"), bp::arg("seconds"), bp::arg("fractions")), - bp::return_internal_reference<>()); - - t.def("format", (string(TimeDuration::*)(string const&) const)(&TimeDuration::format), (bp::arg("fmt"))); - - t.def("fromHash", (void(TimeDuration::*)(Hash const&))(&TimeDuration::fromHash), (bp::arg("hash"))); - - t.def("getDays", (unsigned long int (TimeDuration::*)() const)(&TimeDuration::getDays)); - - t.def("getFractions", - (TimeValue(TimeDuration::*)(karabo::util::TIME_UNITS const) const)(&TimeDuration::getFractions), - (bp::arg("unit") = karabo::util::NANOSEC)); - - t.def("getHours", (unsigned long int (TimeDuration::*)() const)(&TimeDuration::getHours)); - - t.def("getMinutes", (unsigned long int (TimeDuration::*)() const)(&TimeDuration::getMinutes)); - - t.def("getSeconds", (TimeValue(TimeDuration::*)() const)(&TimeDuration::getSeconds)); - - t.def("getTotalHours", (TimeValue(TimeDuration::*)() const)(&TimeDuration::getTotalHours)); - - t.def("getTotalMinutes", (TimeValue(TimeDuration::*)() const)(&TimeDuration::getTotalMinutes)); - - t.def("getTotalSeconds", (TimeValue(TimeDuration::*)() const)(&TimeDuration::getTotalSeconds)); - - t.def("isNull", (bool(TimeDuration::*)() const)(&TimeDuration::isNull)); - - t.def("setDefaultFormat", (void (*)(string const&))(&TimeDuration::setDefaultFormat), (bp::arg("fmt"))); - t.staticmethod("setDefaultFormat"); - - t.def("toHash", (void(TimeDuration::*)(Hash&))(&TimeDuration::toHash), (bp::arg("hash"))); - - t.def(bp::self != bp::self); - t.def(bp::self + bp::self); - t.def(bp::self += bp::self); - t.def(bp::self - bp::self); - t.def(bp::self -= bp::self); - t.def(bp::self / bp::self); - t.def(bp::self < bp::self); - t.def(bp::self <= bp::self); - t.def(bp::self == bp::self); - t.def(bp::self > bp::self); - t.def(bp::self >= bp::self); -} diff --git a/src/karathon/PyUtilTimestamp.cc b/src/karathon/PyUtilTimestamp.cc deleted file mode 100644 index e7509b7221..0000000000 --- a/src/karathon/PyUtilTimestamp.cc +++ /dev/null @@ -1,70 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include -#include - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -void exportPyUtilTimestamp() { - bp::class_ ts("Timestamp", bp::init<>()); - - ts.def(bp::init((bp::arg("e"), bp::arg("t")))); - - ts.def("getSeconds", (unsigned long long const& (Timestamp::*)() const)(&Timestamp::getSeconds), - bp::return_value_policy()); - - ts.def("getFractionalSeconds", (unsigned long long const& (Timestamp::*)() const)(&Timestamp::getFractionalSeconds), - bp::return_value_policy()); - - ts.def("getTrainId", (unsigned long long const& (Timestamp::*)() const)(&Timestamp::getTrainId), - bp::return_value_policy()); - - ts.def("fromHashAttributes", &Timestamp::fromHashAttributes, bp::arg("attributes")); - ts.staticmethod("fromHashAttributes"); - - ts.def("hashAttributesContainTimeInformation", &Timestamp::hashAttributesContainTimeInformation, - bp::arg("attributes")); - ts.staticmethod("hashAttributesContainTimeInformation"); - - ts.def("toIso8601", (string(Timestamp::*)(karabo::util::TIME_UNITS, bool) const)(&Timestamp::toIso8601), - (bp::arg("precision") = karabo::util::MICROSEC, bp::arg("extended") = (bool)(false))); - - ts.def("toIso8601Ext", (string(Timestamp::*)(karabo::util::TIME_UNITS, bool) const)(&Timestamp::toIso8601Ext), - (bp::arg("precision") = karabo::util::MICROSEC, bp::arg("extended") = (bool)(false))); - - ts.def("toFormattedStringLocale", - (string(Timestamp::*)(const string&, const string&, const string&) - const)(&Timestamp::toFormattedStringLocale), - (bp::arg("localeName") = "", bp::arg("format") = "%Y-%b-%d %H:%M:%S", bp::arg("localTimeZone") = "Z")); - - ts.def("toFormattedString", - (string(Timestamp::*)(const string&, const string&) const)(&Timestamp::toFormattedString), - (bp::arg("format") = "%Y-%b-%d %H:%M:%S", bp::arg("localTimeZone") = "Z")); - - ts.def("toTimestamp", (double(Timestamp::*)() const)(&Timestamp::toTimestamp)); - - ts.def("toHashAttributes", (void(Timestamp::*)(Hash::Attributes&) const)(&Timestamp::toHashAttributes), - bp::arg("attributes")); -} diff --git a/src/karathon/PyUtilTrainstamp.cc b/src/karathon/PyUtilTrainstamp.cc deleted file mode 100644 index 469b270eed..0000000000 --- a/src/karathon/PyUtilTrainstamp.cc +++ /dev/null @@ -1,48 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include -#include - -namespace bp = boost::python; -using namespace karabo::util; -using namespace std; - - -void exportPyUtilTrainstamp() { - bp::class_ t("Trainstamp"); - t.def(bp::init<>()); - t.def(bp::init(bp::arg("trainId"))); - - t.def("getTrainId", (unsigned long long const& (Trainstamp::*)() const)(&Trainstamp::getTrainId), - bp::return_value_policy()); - - t.def("hashAttributesContainTimeInformation", &Trainstamp::hashAttributesContainTimeInformation, - bp::arg("attributes")); - t.staticmethod("hashAttributesContainTimeInformation"); - - t.def("fromHashAttributes", (Trainstamp(*)(Hash::Attributes const))(&Trainstamp::fromHashAttributes), - bp::arg("attributes")); - t.staticmethod("fromHashAttributes"); - - t.def("toHashAttributes", (void(Trainstamp::*)(Hash::Attributes&) const)(&Trainstamp::toHashAttributes), - bp::arg("attributes")); -} diff --git a/src/karathon/PyXmsInputOutputChannel.cc b/src/karathon/PyXmsInputOutputChannel.cc deleted file mode 100644 index 4816ec45b5..0000000000 --- a/src/karathon/PyXmsInputOutputChannel.cc +++ /dev/null @@ -1,807 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include "PyXmsInputOutputChannel.hh" - -namespace bp = boost::python; - -namespace karathon { - - - boost::shared_ptr ImageDataWrap::make5(const bp::object& obj, - const karabo::util::Dims& dimensions, - const karabo::xms::EncodingType encoding, - const int bitsPerPixel) { - using namespace karabo::util; - using namespace karabo::xms; - - if (obj.is_none()) { - auto self = boost::make_shared(); - return self; - } else { - PyArrayObject* arr = reinterpret_cast(obj.ptr()); - const NDArray ndarray = Wrapper::fromPyArrayToNDArray(arr); - auto self = boost::make_shared(ndarray, dimensions, encoding, bitsPerPixel); - return self; - } - } - - - bp::object ImageDataWrap::getDataPy(const boost::shared_ptr& self) { - return Wrapper::fromNDArrayToPyArray(self->getData()); - } - - - void ImageDataWrap::setDataPy(const boost::shared_ptr& self, const bp::object& obj) { - PyArrayObject* arr = reinterpret_cast(obj.ptr()); - self->setData(Wrapper::fromPyArrayToNDArray(arr)); - } - - - bp::object ImageDataWrap::getTypePy(const boost::shared_ptr& self) { - return bp::object(static_cast(self->getDataType())); - } - - - void ImageDataWrap::setTypePy(const boost::shared_ptr& self, const bp::object& obj) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - - if (bp::extract(obj).check()) { - std::string type = bp::extract(obj); - reftype = Types::from(type); - } else if (bp::extract(obj).check()) { - karathon::PyTypes::ReferenceType type = bp::extract(obj); - reftype = karathon::PyTypes::to(type); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of setType() of ImageData must be a string or Types enumerated value."); - } - self->setDataType(reftype); - } - - - bp::object ImageDataWrap::getDimensionsPy(const boost::shared_ptr& self) { - karabo::util::Dims dims = self->getDimensions(); - return Wrapper::fromStdVectorToPyTuple(dims.toVector()); - } - - - void ImageDataWrap::setDimensionsPy(const boost::shared_ptr& self, const bp::object& obj) { - if (bp::extract(obj).check()) { - self->setDimensions(bp::extract(obj)); - } else if (bp::extract(obj).check()) { - karabo::util::Dims dims(Wrapper::fromPyListToStdVector(obj)); - self->setDimensions(dims); - } else if (bp::extract(obj).check()) { - karabo::util::Dims dims(Wrapper::fromPyTupleToStdVector(obj)); - self->setDimensions(dims); - } else { - throw KARABO_PYTHON_EXCEPTION(std::string("Unsupported argument type '") + obj.ptr()->ob_type->tp_name + - "'"); - } - } - - - bp::object ImageDataWrap::getDimensionTypesPy(const boost::shared_ptr& self) { - return Wrapper::fromStdVectorToPyTuple(self->getDimensionTypes()); - } - - - void ImageDataWrap::setDimensionTypesPy(const boost::shared_ptr& self, - const bp::object& obj) { - if (bp::extract(obj).check()) { - bp::ssize_t size = bp::len(obj); - std::vector dimTypes(size); - for (int i = 0; i < size; i++) { - dimTypes[i] = bp::extract(obj[i]); - } - self->setDimensionTypes(dimTypes); - } else if (bp::extract(obj).check()) { - std::vector dimTypes = Wrapper::fromPyTupleToStdVector(obj); - self->setDimensionTypes(dimTypes); - } else { - throw KARABO_PYTHON_EXCEPTION(std::string("Unsupported argument type '") + obj.ptr()->ob_type->tp_name + - "'"); - } - } - - - bp::object ImageDataWrap::getROIOffsetsPy(const boost::shared_ptr& self) { - karabo::util::Dims offsets = self->getROIOffsets(); - return Wrapper::fromStdVectorToPyTuple(offsets.toVector()); - } - - - void ImageDataWrap::setROIOffsetsPy(const boost::shared_ptr& self, const bp::object& obj) { - if (bp::extract(obj).check()) { - self->setROIOffsets(bp::extract(obj)); - } else if (bp::extract(obj).check()) { - karabo::util::Dims offsets(Wrapper::fromPyListToStdVector(obj)); - self->setROIOffsets(offsets); - } else if (bp::extract(obj).check()) { - karabo::util::Dims offsets(Wrapper::fromPyTupleToStdVector(obj)); - self->setROIOffsets(offsets); - } else { - throw KARABO_PYTHON_EXCEPTION(std::string("Unsupported argument type '") + obj.ptr()->ob_type->tp_name + - "'"); - } - } - - - bp::object ImageDataWrap::getBinningPy(const boost::shared_ptr& self) { - karabo::util::Dims binning = self->getBinning(); - return Wrapper::fromStdVectorToPyTuple(binning.toVector()); - } - - - void ImageDataWrap::setBinningPy(const boost::shared_ptr& self, const bp::object& obj) { - if (bp::extract(obj).check()) { - self->setBinning(bp::extract(obj)); - } else if (bp::extract(obj).check()) { - karabo::util::Dims binning(Wrapper::fromPyListToStdVector(obj)); - self->setBinning(binning); - } else if (bp::extract(obj).check()) { - karabo::util::Dims binning(Wrapper::fromPyTupleToStdVector(obj)); - self->setBinning(binning); - } else { - throw KARABO_PYTHON_EXCEPTION(std::string("Unsupported argument type '") + obj.ptr()->ob_type->tp_name + - "'"); - } - } - - - bp::object ImageDataWrap::getEncodingPy(const boost::shared_ptr& self) { - return bp::object(karabo::xms::EncodingType(self->getEncoding())); - } - - - ChannelMetaData::ChannelMetaData(const bp::object& src, const bp::object& ts) - : karabo::xms::Memory::MetaData(bp::extract(src), bp::extract(ts)) {} - - - void ChannelMetaData::setSource(const bp::object& src) { - karabo::xms::Memory::MetaData::setSource(bp::extract(src)); - } - - - bp::object ChannelMetaData::getSource() { - return bp::object(karabo::xms::Memory::MetaData::getSource()); - } - - - void ChannelMetaData::setTimestamp(const bp::object& ts) { - karabo::xms::Memory::MetaData::setTimestamp(bp::extract(ts)); - } - - - bp::object ChannelMetaData::getTimestamp() { - return bp::object(karabo::xms::Memory::MetaData::getTimestamp()); - } - - - void OutputChannelWrap::registerIOEventHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - using Wrap = HandlerWrap; - self->registerIOEventHandler(Wrap(handler, "IOEvent")); - } - - - void OutputChannelWrap::registerShowConnectionsHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - HandlerWrap&> wrappedHandler(handler, "show connections"); - ScopedGILRelease noGil; - // Setting the handler might overwrite and thus destruct a previous handler. - // That one's destruction might acquire the GIL via the destructor of HandlerWrap. - // So better release the GIL here (although the deadlock has not been seen without releasing). - self->registerShowConnectionsHandler( - std::move(wrappedHandler)); // move for once when handler registration will take rvalue reference... - } - - void OutputChannelWrap::registerShowStatisticsHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - HandlerWrapVullVull wrappedHandler(handler, "show statistics"); - ScopedGILRelease noGil; - // Setting the handler might overwrite and thus destruct a previous handler. - // That one's destruction might acquire the GIL via the destructor of HandlerWrap. - self->registerShowStatisticsHandler(wrappedHandler); - } - - void OutputChannelWrap::registerSharedInputSelectorPy(const boost::shared_ptr& self, - const bp::object& handler) { - karabo::xms::SharedInputSelector selector; - if (!handler.is_none()) { - selector = ReturnHandlerWrap&>(handler, "sharedInputSelector"); - } // else we reset the selection - self->registerSharedInputSelector(std::move(selector)); - } - - void OutputChannelWrap::writePy(const boost::shared_ptr& self, const bp::object& data, - const bp::object& meta, bool copyAllData) { - if (!bp::extract(meta).check()) { - throw KARABO_PYTHON_EXCEPTION( - "Unsupported parameter type for parameter 'meta'. Needs to be ChannelMetaData"); - } - - if (!bp::extract(data).check()) { - throw KARABO_PYTHON_EXCEPTION("Unsupported parameter type for parameter 'data'. Needs to be Hash"); - } - // we need to copy here before the GIL release, otherwise data might be altered during writing. - const karabo::util::Hash dataHash = bp::extract(data); - const karabo::xms::Memory::MetaData metaData = bp::extract(meta); - ScopedGILRelease nogil; - self->write(dataHash, metaData, copyAllData); - } - - - void OutputChannelWrap::updatePy(const boost::shared_ptr& self, bool safeNDArray) { - ScopedGILRelease nogil; - self->update(safeNDArray); - } - - void OutputChannelWrap::asyncUpdatePy(const boost::shared_ptr& self, bool safeNDArray, - const bp::object& readyHandler) { - boost::function handler; - if (readyHandler.is_none()) { - handler = []() {}; - } else { - handler = HandlerWrap<>(readyHandler, "asyncUpdate"); - } - ScopedGILRelease nogil; // This asyncUpdate is only partially async and can block, so release GIL - self->asyncUpdate(safeNDArray, std::move(handler)); - } - - - void OutputChannelWrap::signalEndOfStreamPy(const boost::shared_ptr& self) { - ScopedGILRelease nogil; - self->signalEndOfStream(); - } - - - void OutputChannelWrap::asyncSignalEndOfStreamPy(const boost::shared_ptr& self, - const bp::object& readyHandler) { - boost::function handler; - if (readyHandler.is_none()) { - handler = []() {}; - } else { - handler = HandlerWrap<>(readyHandler, "asyncSignalEndOfStream"); - } - ScopedGILRelease nogil; - self->asyncSignalEndOfStream(std::move(handler)); - } - - - bp::object OutputChannelWrap::create(const std::string& instanceId, const std::string& channelName, - const karabo::util::Hash& channelConfig) { - using namespace karabo::xms; - using namespace karabo::util; - OutputChannel::Pointer channel = Configurator::create("OutputChannel", channelConfig, 0); - channel->setInstanceIdAndName(instanceId, channelName); - channel->initialize(); - return bp::object(channel); - } - - - void InputChannelWrap::registerInputHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - self->registerInputHandler(HandlerWrap(handler, "input")); - } - - - void InputChannelWrap::registerConnectionTrackerPy(const boost::shared_ptr& self, - const bp::object& statusTracker) { - using Wrap = HandlerWrap; - self->registerConnectionTracker(Wrap(statusTracker, "channelStatusTracker")); - } - - - void InputChannelWrap::registerDataHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - self->registerDataHandler(InputChannelWrap::DataHandlerWrap(handler, "data")); - } - - - void InputChannelWrap::registerEndOfStreamEventHandlerPy(const boost::shared_ptr& self, - const bp::object& handler) { - self->registerEndOfStreamEventHandler(HandlerWrap(handler, "EOS")); - } - - - bp::object InputChannelWrap::getConnectionStatusPy(const boost::shared_ptr& self) { - typedef std::unordered_map ConnStatusMap; - ConnStatusMap csmap = self->getConnectionStatus(); - bp::dict d; - for (auto it = csmap.begin(); it != csmap.end(); ++it) { - d[it->first] = bp::object(it->second); - } - return bp::object(d); - } - - - bp::object InputChannelWrap::getConnectedOutputChannelsPy( - const boost::shared_ptr& self) { - typedef std::map OutputChannels; - const OutputChannels& ochannels = self->getConnectedOutputChannels(); - bp::dict d; - for (OutputChannels::const_iterator it = ochannels.begin(); it != ochannels.end(); ++it) { - d[it->first] = bp::object(it->second); - } - return bp::object(d); - } - - - bp::object InputChannelWrap::readPy(const boost::shared_ptr& self, size_t idx) { - karabo::util::Hash::Pointer hash; - { - // Release the GIL for the potentially blocking read() call. - ScopedGILRelease nogil; - hash = self->read(idx); - } - return bp::object(hash); - } - - - bp::object InputChannelWrap::connectSyncPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo) { - std::string msg; - { - ScopedGILRelease nogil; - auto promi = std::make_shared>(); - auto futur = promi->get_future(); - self->connect(outputChannelInfo, [promi](const boost::system::error_code& e) { promi->set_value(e); }); - auto e = futur.get(); - if (e.value()) msg = e.message(); - } - return bp::object(msg); - } - - - void InputChannelWrap::connectPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo, const bp::object& handler) { - auto wrappedHandler = HandlerWrap(handler, "Connect"); - ScopedGILRelease nogil; - self->connect(outputChannelInfo, [wrappedHandler](const boost::system::error_code& e) { - std::string msg; - if (e.value()) msg = e.message(); - wrappedHandler(msg); - }); - } - - - void InputChannelWrap::disconnectPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo) { - ScopedGILRelease nogil; - self->disconnect(outputChannelInfo); - } - - - bp::object InputChannelWrap::getMetaData(const boost::shared_ptr& self) { - auto ret = boost::make_shared>(); - { - ScopedGILRelease nogil; - std::vector md = self->getMetaData(); - for (auto it = md.begin(); it != md.end(); ++it) { - // TODO: Properly wrap MetaData object - currently this will be visible in Python as hash - ret->push_back(*reinterpret_cast(&*it)); - } - } - return bp::object(ret); - } - - - InputChannelWrap::DataHandlerWrap::DataHandlerWrap(const bp::object& handler, char const* const where) - : HandlerWrap(handler, where) {} - - - void InputChannelWrap::DataHandlerWrap::operator()(const karabo::util::Hash& data, - const karabo::xms::InputChannel::MetaData& meta) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - // TODO: wrap MetaData to expose full interface, right now this makes it look like a Hash within Python - // (Then one can get rid of InputChannelWrap::DataHandlerWrap and directly - // use HandlerWrap) - (*m_handler)(data, *(reinterpret_cast(&meta))); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); // from Wrapper.hh - } catch (...) { - KARABO_RETHROW - } - } - - - bp::object InputChannelWrap::create(const std::string& instanceId, const std::string& channelName, - const karabo::util::Hash& channelConfig) { - using namespace karabo::xms; - using namespace karabo::util; - InputChannel::Pointer channel = Configurator::create("InputChannel", channelConfig); - channel->setInstanceId(instanceId + ":" + channelName); - return bp::object(channel); - } -} // namespace karathon - - -template -void exportPyXmsImageData() { - const std::string typeName( - karabo::util::Types::convert(typeid(T))); -} - - -void exportPyXmsInputOutputChannel() { - { - bp::enum_("Encoding") - .value("UNDEFINED", karabo::xms::Encoding::UNDEFINED) - .value("GRAY", karabo::xms::Encoding::GRAY) - .value("RGB", karabo::xms::Encoding::RGB) - .value("RGBA", karabo::xms::Encoding::RGBA) - .value("BGR", karabo::xms::Encoding::BGR) - .value("BGRA", karabo::xms::Encoding::BGRA) - .value("CMYK", karabo::xms::Encoding::CMYK) - .value("YUV", karabo::xms::Encoding::YUV) - .value("BAYER", karabo::xms::Encoding::BAYER) - .value("JPEG", karabo::xms::Encoding::JPEG) - .value("PNG", karabo::xms::Encoding::PNG) - .value("BMP", karabo::xms::Encoding::BMP) - .value("TIFF", karabo::xms::Encoding::TIFF) - .export_values(); - } - - { - bp::enum_("Rotation") - .value("UNDEFINED", karabo::xms::Rotation::UNDEFINED) - .value("ROT_0", karabo::xms::Rotation::ROT_0) - .value("ROT_90", karabo::xms::Rotation::ROT_90) - .value("ROT_180", karabo::xms::Rotation::ROT_180) - .value("ROT_270", karabo::xms::Rotation::ROT_270) - .export_values(); - } - - { - bp::class_>("ImageData", bp::init<>()) - - .def("__init__", bp::make_constructor(&karathon::ImageDataWrap::make5, bp::default_call_policies(), - (bp::arg("array"), bp::arg("dims") = karabo::util::Dims(), - bp::arg("encoding") = karabo::xms::Encoding::UNDEFINED, - bp::arg("bitsPerPixel") = 0))) - - .def("getData", &karathon::ImageDataWrap::getDataPy) - - .def("setData", &karathon::ImageDataWrap::setDataPy, (bp::arg("data"))) - - .def("getType", &karathon::ImageDataWrap::getTypePy) - - .def("setType", &karathon::ImageDataWrap::setTypePy, (bp::arg("dtype"))) - - .def("getDimensions", &karathon::ImageDataWrap::getDimensionsPy) - - .def("setDimensions", &karathon::ImageDataWrap::setDimensionsPy, (bp::arg("dims"))) - - .def("getDimensionTypes", &karathon::ImageDataWrap::getDimensionTypesPy) - - .def("setDimensionTypes", &karathon::ImageDataWrap::setDimensionTypesPy, (bp::arg("listOfDimTypes"))) - - .def("getROIOffsets", &karathon::ImageDataWrap::getROIOffsetsPy) - - .def("setROIOffsets", &karathon::ImageDataWrap::setROIOffsetsPy, (bp::arg("offsets"))) - - .def("getBinning", &karathon::ImageDataWrap::getBinningPy) - - .def("setBinning", &karathon::ImageDataWrap::setBinningPy, (bp::arg("binning"))) - - .def("getRotation", &karabo::xms::ImageData::getRotation) - - .def("setRotation", &karabo::xms::ImageData::setRotation, (bp::arg("rotation"))) - - .def("getFlipX", &karabo::xms::ImageData::getFlipX) - - .def("setFlipX", &karabo::xms::ImageData::setFlipX, (bp::arg("flipX"))) - - .def("getFlipY", &karabo::xms::ImageData::getFlipY) - - .def("setFlipY", &karabo::xms::ImageData::setFlipY, (bp::arg("flipY"))) - - .def("getBitsPerPixel", &karabo::xms::ImageData::getBitsPerPixel) - - .def("setBitsPerPixel", &karabo::xms::ImageData::setBitsPerPixel, (bp::arg("bitsPerPixel"))) - - .def("getEncoding", &karathon::ImageDataWrap::getEncodingPy) - - .def("setEncoding", &karabo::xms::ImageData::setEncoding, (bp::arg("encoding"))) - - .def("isIndexable", &karabo::xms::ImageData::isIndexable) - - .def("getDimensionScales", &karabo::xms::ImageData::getDimensionScales, - bp::return_value_policy()) - - .def("setDimensionScales", &karabo::xms::ImageData::setDimensionScales, (bp::arg("scales"))); - } - { - bp::implicitly_convertible(); - bp::class_("IMAGEDATA_ELEMENT", - bp::init((bp::arg("expected")))) - - .def("key", &karabo::xms::ImageDataElement::key, (bp::arg("key")), bp::return_internal_reference<>()) - - .def("displayedName", &karabo::xms::ImageDataElement::displayedName, bp::arg("name"), - bp::return_internal_reference<>()) - - .def("description", &karabo::xms::ImageDataElement::description, bp::arg("desc"), - bp::return_internal_reference<>()) - - // .def("setDefaultValue", &karathon::ImageDataElementWrap().setDefaultValue - // , (bp::arg("subKey"), bp::arg("defaultValue")) - // , bp::return_internal_reference<> ()) - - - .def("observerAccess", &karabo::xms::ImageDataElement::observerAccess, bp::return_internal_reference<>()) - - .def("userAccess", &karabo::xms::ImageDataElement::userAccess, bp::return_internal_reference<>()) - - .def("operatorAccess", &karabo::xms::ImageDataElement::operatorAccess, bp::return_internal_reference<>()) - - .def("expertAccess", &karabo::xms::ImageDataElement::expertAccess, bp::return_internal_reference<>()) - - .def("adminAccess", &karabo::xms::ImageDataElement::adminAccess, bp::return_internal_reference<>()) - - .def("skipValidation", &karabo::xms::ImageDataElement::skipValidation, bp::return_internal_reference<>()) - - .def("commit", &karabo::xms::ImageDataElement::commit, bp::return_internal_reference<>()) - - .def("setDimensionScales", &karabo::xms::ImageDataElement::setDimensionScales, (bp::arg("scales")), - bp::return_internal_reference<>()) - - .def("setDimensions", &karathon::ImageDataElementWrap::setDimensions, (bp::arg("dims")), - bp::return_internal_reference<>(), - "h.setDimensions(dims) set the shape of an image in the schema. This is required by the DAQ," - "otherwise silent data-loss or segfaults can occur. The shape can be a list or string with 2 or 3 " - "dimensions (for color images).\nExample:\n\t" - "IMAGEDATA_ELEMENT(s)\n\t\t.key('data.image')\n\t\t.setDimensions('480,640,3')\n\t\t.commit()\n\t" - "IMAGEDATA_ELEMENT(s)\n\t\t.key('data.image')\n\t\t.setDimensions([480,640])\n\t\t.commit()") - - .def("setType", &karathon::ImageDataElementWrap::setType, (bp::arg("type")), - bp::return_internal_reference<>(), - "h.setType(type) set the datatype of an image in the schema. This is required by the DAQ," - "otherwise silent data-loss or segfaults can occur. The type can be a member of the 'Types' " - "class or a string (all capitals).\nExample:\n\t" - "IMAGEDATA_ELEMENT(s)\n\t\t.key('data.image')\n\t\t.setType('UINT16')\n\t\t.commit()\n\t" - "IMAGEDATA_ELEMENT(s)\n\t\t.key('data.image')\n\t\t.setType(Types.UINT16)\n\t\t.commit()") - - .def("setEncoding", &karathon::ImageDataElementWrap::setEncoding, (bp::arg("encoding")), - bp::return_internal_reference<>(), - "h.setEncoding(encoding) set the encoding of an image in the schema. The encoding name must be a " - "string (all capitals).\nExample:\n\t" - "IMAGEDATA_ELEMENT(s)\n\t\t.key('data.image')\n\t\t.setEncoding('RGB')\n\t\t.commit()") - - .def("setAllowedActions", &karathon::ImageDataElementWrap::setAllowedActions, (bp::arg("actions")), - bp::return_internal_reference<>(), - "Specify one or more actions that are allowed on this node.\n" - "If a Karabo device specifies allowed actions for a node,\n" - "that means that it offers a specific slot interface to operate\n" - "on this node. Which allowed actions require which interface\n" - "is defined elsewhere."); - } - - - { - bp::class_("ChannelMetaData", - bp::init()) - .def("setSource", &karathon::ChannelMetaData::setSource, (bp::arg("source"))) - .def("getSource", &karathon::ChannelMetaData::getSource) - .def("setTimestamp", &karathon::ChannelMetaData::setTimestamp, (bp::arg("timestamp"))) - .def("getTimestamp", &karathon::ChannelMetaData::getTimestamp); - } - - { - bp::class_, boost::noncopyable>( - "OutputChannel", bp::no_init) - - .def("setInstanceIdAndName", &karabo::xms::OutputChannel::setInstanceIdAndName, - (bp::arg("instanceId"), bp::arg("name"))) - - .def("getInstanceId", &karabo::xms::OutputChannel::getInstanceId, - bp::return_value_policy()) - - .def("getInstanceIdName", &karabo::xms::OutputChannel::getInstanceIdName) - - .def("getInitialConfiguration", &karabo::xms::OutputChannel::getInitialConfiguration) - - .def("registerIOEventHandler", &karathon::OutputChannelWrap().registerIOEventHandlerPy) - - .def("getInformation", &karabo::xms::OutputChannel::getInformation) - - .def("hasRegisteredCopyInputChannel", &karabo::xms::OutputChannel::hasRegisteredCopyInputChannel, - (bp::arg("instanceId"))) - - .def("hasRegisteredSharedInputChannel", &karabo::xms::OutputChannel::hasRegisteredSharedInputChannel, - (bp::arg("instanceId"))) - - .def("write", &karathon::OutputChannelWrap().writePy, - (bp::arg("data"), bp::arg("meta"), bp::arg("copyAllData") = false), - "data - a Hash with the data to write\n" - "meta - ChannelMetaData\n" - "copyAllData - unused\n\n" - "Note 1: Any NDArray/ImageData inside data must stay untouched at least\n" - " until update() has been called. See also the documentation of the\n" - " safeNDArray flag of the update() method.\n" - "Note 2: The methods 'write(..)', 'update()' and 'signalEndOfStream()'\n" - " must not be called concurrently") - - .def("update", &karathon::OutputChannelWrap().updatePy, (bp::arg("safeNDArray") = false), - "Update the output channel, i.e. send all data over the wire that was\n" - "previously written by calling write(..).\n\n" - "safeNdarray - boolean to indicate whether all ndarrays inside the Hash\n" - " passed to write(..) before are 'safe', i.e. their memory\n" - " will not be referred to elsewhere after update is finished.\n" - " Default is 'false', 'true' can avoid safety copies of NDArray\n" - " content when data is queued or sent locally.\n" - "Note: The methods 'write(..)', 'update()' and 'signalEndOfStream()' must\n" - " not be called concurrently") - - .def("asyncUpdate", &karathon::OutputChannelWrap().asyncUpdatePy, - (bp::arg("safeNDArray") = false, bp::arg("readyHandler") = bp::object()), - "Semi-asynchronously update the output channel, i.e. asynchronously send all\n" - "data over the wire that was previously written by calling write(...), but\n" - "block as long as any of the connected InputChannels requires if wait is\n" - "configured.\n" - "safeNDArray - boolean to indicate whether all NDArrays inside the Hash\n" - " passed to write(..) before are 'safe', i.e. their memory will\n" - " not be referred to elsewhere after update is finished.\n" - " Default is 'false', 'true' can avoid safety copies of NDArray\n" - " content when data is queued or sent locally.\n" - "readyHandler - callback when data (that is not queued) has been sent and\n" - " thus even NDArray data inside it can be re-used again\n" - " (except if safeNDArray was set to 'true' in which case its\n" - " memory may still be used in a queue).\n\n" - "Thread safety:\n" - "All the 'write(..)' methods, '[async]Update(..)' and\n" - "'[async]SignalEndOfStream(..)' must not be called concurrently.") - - .def("signalEndOfStream", &karathon::OutputChannelWrap().signalEndOfStreamPy, - "Send end-of-stream (EOS) notification to all connected input channels to\n" - "indicate a logical break in the data stream.\n" - "Note: The methods 'write(..)', 'update()' and 'signalEndOfStream()' must not\n" - " be called concurrently") - - .def("asyncSignalEndOfStream", &karathon::OutputChannelWrap().asyncSignalEndOfStreamPy, - (bp::arg("readyHandler") = bp::object()), - "Asynchonously send end-of-stream (EOS) notification to all connected input\n" - "channels to indicate a logical break in the data stream.\n\n" - "readyHandler - callback when notification has been sent or queued\n\n" - "Thread safety:\n" - "All the 'write(..)' methods, '[async]Update(..)' and\n" - "'[async]SignalEndOfStream(..)' must not be called concurrently.") - - .def("registerShowConnectionsHandler", &karathon::OutputChannelWrap().registerShowConnectionsHandlerPy, - (bp::arg("handler")), - "Register a handler to be called when the 'connection' table changes.\n" - "Argument of the handler is a list of Hash as described by the row schema\n" - "of the 'connection' table") - - .def("registerShowStatisticsHandler", &karathon::OutputChannelWrap().registerShowStatisticsHandlerPy, - (bp::arg("handler")), - "Register a handler to be regularly called to update written and read bytes.\n" - "Argument of the handler are two lists of numbers: bytes read from and written to\n" - "connected channels, in the same order as in the connection table.") - - .def("registerSharedInputSelector", &karathon::OutputChannelWrap().registerSharedInputSelectorPy, - (bp::arg("selector")), - R"(Register handler that selects which of the connected input channels that have -dataDistribution = "shared" is to be served. - -The handler will be called during update() with the ids of the connected -"shared" input channels (e.g. "deviceId:input") as argument. The returned -channel id will receive the data. If an empty string or an unknown id is -returned, the data will be dropped. - -:param selector takes a list of str as argument and shall return str)") - .def("create", &karathon::OutputChannelWrap::create, - (bp::arg("instanceId"), bp::arg("channelName"), bp::arg("channelConfig"))) - .staticmethod("create"); - } - - { - bp::implicitly_convertible(); - bp::class_("OUTPUT_CHANNEL", - bp::init((bp::arg("expected")))) - - .def("key", &karabo::xms::OutputChannelElement::key, (bp::arg("key")), bp::return_internal_reference<>()) - - .def("displayedName", &karabo::xms::OutputChannelElement::displayedName, (bp::arg("name")), - bp::return_internal_reference<>()) - - .def("description", &karabo::xms::OutputChannelElement::description, (bp::arg("description")), - bp::return_internal_reference<>()) - - .def("dataSchema", &karabo::xms::OutputChannelElement::dataSchema, (bp::arg("schema")), - bp::return_internal_reference<>()) - - .def("commit", &karabo::xms::OutputChannelElement::commit, bp::return_internal_reference<>()) - - ; - } - - { - bp::class_, boost::noncopyable>( - "InputChannel", bp::no_init) - - .def("reconfigure", &karabo::xms::InputChannel::reconfigure, (bp::arg("configuration"))) - - .def("setInstanceId", &karabo::xms::InputChannel::setInstanceId, (bp::arg("instanceId"))) - - .def("getInstanceId", &karabo::xms::InputChannel::getInstanceId, - bp::return_value_policy()) - - .def("registerDataHandler", &karathon::InputChannelWrap().registerDataHandlerPy) - - .def("registerInputHandler", &karathon::InputChannelWrap().registerInputHandlerPy) - - .def("registerEndOfStreamEventHandler", &karathon::InputChannelWrap().registerEndOfStreamEventHandlerPy) - - .def("registerConnectionTracker", &karathon::InputChannelWrap().registerConnectionTrackerPy, - "Register a handler to track the status of the connections to\nthe configured output channels.\n" - "The handler has two arguments:\n" - " * the output channel string like ':'\n" - " * the ConnectionStatus") - - .def("getConnectionStatus", &karathon::InputChannelWrap().getConnectionStatusPy) - - .def("getConnectedOutputChannels", &karathon::InputChannelWrap().getConnectedOutputChannelsPy) - - .def("read", &karathon::InputChannelWrap().readPy, (bp::arg("idx"))) - - .def("size", &karabo::xms::InputChannel::size) - - .def("getMinimumNumberOfData", &karabo::xms::InputChannel::getMinimumNumberOfData) - - .def("connectSync", &karathon::InputChannelWrap().connectSyncPy, (bp::arg("outputChannelInfo"))) - - .def("connect", &karathon::InputChannelWrap().connectPy, - (bp::arg("outputChannelInfo"), bp::arg("handler") = bp::object())) - - .def("disconnect", &karathon::InputChannelWrap().disconnectPy, (bp::arg("outputChannelInfo"))) - - .def("getMetaData", &karathon::InputChannelWrap().getMetaData) - - .def("create", &karathon::InputChannelWrap::create, - (bp::arg("instanceId"), bp::arg("channelName"), bp::arg("channelConfig"))) - .staticmethod("create"); - } - - { - bp::implicitly_convertible(); - bp::class_("INPUT_CHANNEL", - bp::init((bp::arg("expected")))) - - .def("key", &karabo::xms::InputChannelElement::key, (bp::arg("key")), bp::return_internal_reference<>()) - - .def("displayedName", &karabo::xms::InputChannelElement::displayedName, (bp::arg("name")), - bp::return_internal_reference<>()) - - .def("description", &karabo::xms::InputChannelElement::description, (bp::arg("description")), - bp::return_internal_reference<>()) - - .def("dataSchema", &karabo::xms::InputChannelElement::dataSchema, (bp::arg("schema")), - bp::return_internal_reference<>()) - - .def("commit", &karabo::xms::InputChannelElement::commit, bp::return_internal_reference<>()) - - ; - } -} diff --git a/src/karathon/PyXmsInputOutputChannel.hh b/src/karathon/PyXmsInputOutputChannel.hh deleted file mode 100644 index 60d5bdf905..0000000000 --- a/src/karathon/PyXmsInputOutputChannel.hh +++ /dev/null @@ -1,204 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef KARATHON_PYXMSINPUTOUTPUTCHANNEL_HH -#define KARATHON_PYXMSINPUTOUTPUTCHANNEL_HH - -#include -#include -#include -#include -#include -#include -#include - -#include "DimsWrap.hh" -#include "FromNumpy.hh" -#include "PythonFactoryMacros.hh" -#include "ScopedGILAcquire.hh" -#include "ScopedGILRelease.hh" -#include "ToNumpy.hh" -#include "Wrapper.hh" - -#define PY_ARRAY_UNIQUE_SYMBOL karabo_ARRAY_API -#define NO_IMPORT_ARRAY -#include - -namespace bp = boost::python; - -namespace karathon { - - struct ImageDataWrap : public karabo::xms::ImageData { - static boost::shared_ptr make5( - const bp::object& obj, const karabo::util::Dims& dimensions = karabo::util::Dims(), - const karabo::xms::EncodingType encoding = karabo::xms::Encoding::UNDEFINED, const int bitsPerPixel = 0); - static bp::object getDataPy(const boost::shared_ptr& self); - static void setDataPy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getTypePy(const boost::shared_ptr& self); - static void setTypePy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getDimensionsPy(const boost::shared_ptr& self); - static void setDimensionsPy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getDimensionTypesPy(const boost::shared_ptr& self); - static void setDimensionTypesPy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getROIOffsetsPy(const boost::shared_ptr& self); - static void setROIOffsetsPy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getBinningPy(const boost::shared_ptr& self); - static void setBinningPy(const boost::shared_ptr& self, const bp::object& obj); - static bp::object getEncodingPy(const boost::shared_ptr& self); - }; - - struct ImageDataElementWrap { - static karabo::xms::ImageDataElement& setType(karabo::xms::ImageDataElement& self, const bp::object& obj) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - - // If data type was given as string - if (bp::extract(obj).check()) { - std::string type = bp::extract(obj); - reftype = Types::from(type); - // If data type was given as Type - } else if (bp::extract(obj).check()) { - karathon::PyTypes::ReferenceType type = bp::extract(obj); - reftype = karathon::PyTypes::to(type); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of setType() of ImageDataElement must be a string or Types enumerated value."); - } - return self.setType(reftype); - } - - static karabo::xms::ImageDataElement& setDimensions(karabo::xms::ImageDataElement& self, - const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - // If image dimensions were given as string - return self.setDimensions(bp::extract(obj)); - } else if (PyList_Check(obj.ptr())) { - // If image dimensions were given as list - return self.setDimensions(karathon::Wrapper::fromPyListToStdVector(obj)); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of setDimensions() of ImageDataElement must be a list or a string"); - } - } - - static karabo::xms::ImageDataElement& setEncoding(karabo::xms::ImageDataElement& self, const bp::object& obj) { - using namespace karabo::xms; - EncodingType encType = EncodingType::UNDEFINED; - - // If image encoding type is given as string - if (PyUnicode_Check(obj.ptr())) { - // Create look-up table to translate string-keys to EncodingType - std::map encLuT; - encLuT["UNDEFINED"] = EncodingType::UNDEFINED; - encLuT["GRAY"] = EncodingType::GRAY; - encLuT["RGB"] = EncodingType::RGB; - encLuT["RGBA"] = EncodingType::RGBA; - encLuT["BGR"] = EncodingType::BGR; - encLuT["BGRA"] = EncodingType::BGRA; - encLuT["CMYK"] = EncodingType::CMYK; - encLuT["YUV"] = EncodingType::YUV; - encLuT["BAYER"] = EncodingType::BAYER; - encLuT["JPEG"] = EncodingType::JPEG; - encLuT["PNG"] = EncodingType::PNG; - encLuT["BMP"] = EncodingType::BMP; - encLuT["TIFF"] = EncodingType::TIFF; - // Look up the supplied key in the LUT - encType = encLuT[bp::extract(obj)]; - // If data type was given as integer - } else if (bp::extract(obj).check()) { - encType = bp::extract(obj); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of setEncoding() of ImageDataElement must be an unsigned integer or string"); - } - return self.setEncoding(encType); - } - - static karabo::xms::ImageDataElement& setAllowedActions(karabo::xms::ImageDataElement& self, - const bp::object& actions) { - // Accept any Python iterable that provides strings - return self.setAllowedActions(karathon::Wrapper::fromPyIterableToCppContainer(actions)); - } - }; - - class ChannelMetaData : public karabo::xms::Memory::MetaData { - public: - ChannelMetaData(const bp::object& src, const bp::object& ts); - void setSource(const bp::object& src); - bp::object getSource(); - void setTimestamp(const bp::object& ts); - bp::object getTimestamp(); - }; - - struct OutputChannelWrap { - static bp::object create(const std::string& instanceId, const std::string& channelName, - const karabo::util::Hash& channelConfig); - static void registerIOEventHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void writePy(const boost::shared_ptr& self, const bp::object& data, - const bp::object& meta, bool copyAllData); - static void updatePy(const boost::shared_ptr& self, bool safeNDArray); - static void asyncUpdatePy(const boost::shared_ptr& self, bool safeNDArray, - const bp::object& readyHandler); - static void signalEndOfStreamPy(const boost::shared_ptr& self); - static void asyncSignalEndOfStreamPy(const boost::shared_ptr& self, - const bp::object& readyHandler); - static void registerShowConnectionsHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void registerShowStatisticsHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void registerSharedInputSelectorPy(const boost::shared_ptr& self, - const bp::object& handler); - }; - - struct InputChannelWrap { - static bp::object create(const std::string& instanceId, const std::string& channelName, - const karabo::util::Hash& channelConfig); - // Special handler wrap to cast in operator() - class DataHandlerWrap - : public HandlerWrap { - public: - DataHandlerWrap(const bp::object& handler, char const* const where); - - void operator()(const karabo::util::Hash& data, const karabo::xms::InputChannel::MetaData& meta) const; - }; - - static void registerDataHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void registerInputHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void registerEndOfStreamEventHandlerPy(const boost::shared_ptr& self, - const bp::object& handler); - static void registerConnectionTrackerPy(const boost::shared_ptr& self, - const bp::object& handler); - static bp::object getConnectionStatusPy(const boost::shared_ptr& self); - static bp::object getConnectedOutputChannelsPy(const boost::shared_ptr& self); - static bp::object readPy(const boost::shared_ptr& self, size_t idx); - static void connectPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo, const bp::object& handler = bp::object()); - static bp::object connectSyncPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo); - static void disconnectPy(const boost::shared_ptr& self, - const karabo::util::Hash& outputChannelInfo); - static bp::object getMetaData(const boost::shared_ptr& self); - }; - -} // namespace karathon - - -#endif /* KARATHON_PYXMSINPUTOUTPUTCHANNEL_HH */ diff --git a/src/karathon/PyXmsSignalSlotable.cc b/src/karathon/PyXmsSignalSlotable.cc deleted file mode 100644 index 49b333b935..0000000000 --- a/src/karathon/PyXmsSignalSlotable.cc +++ /dev/null @@ -1,266 +0,0 @@ -/* - * $Id$ - * - * Author: , - * contributions by - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include - -#include "SignalSlotableWrap.hh" - -using namespace karabo::util; -using namespace karabo::io; -using namespace karabo::xms; -using namespace karathon; -using namespace std; -namespace bp = boost::python; - - -void exportPyXmsSignalSlotable() { // exposing karabo::xms::SignalSlotable - bp::class_, boost::noncopyable>("Slot", bp::no_init) - .def("getInstanceIdOfSender", (const std::string& (Slot::*)() const) & Slot::getInstanceIdOfSender, - bp::return_value_policy()); - - bp::class_("Requestor", bp::no_init) - .def("waitForReply", (&SignalSlotableWrap::RequestorWrap::waitForReply), (bp::arg("milliseconds"))) - - .def("receiveAsync", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy, - (bp::arg("replyCallback"), bp::arg("errorCallback") = bp::object(), bp::arg("timeoutMs") = bp::object(), - bp::arg("numCallbackArgs") = bp::object()), - "Asynchronously receive the reply to the requested slot via a callback\n\n" - "replyCallback - called when slot reply arrives, argument number must match number replied by slot\n" - "errorCallback - if specified, called when the slot replies an error or the reply times out,\n" - " will receive two str arguments:\n" - " short description of the problem and details (e.g. stack trace)\n" - "timeoutMs - specify timeout in milliseconds (otherwise a long default is used)\n" - "numCallbackArgs - only needed to specify if number of arguments cannot be deduced from replyCallback") - // Keep the following (with number of return arguments in function name, but without error handling) for - // backward compatibility - .def("receiveAsync0", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy0, (bp::arg("replyCallback")), - "Use receiveAsync instead") - .def("receiveAsync1", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy1, (bp::arg("replyCallback")), - "Use receiveAsync instead") - .def("receiveAsync2", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy2, (bp::arg("replyCallback")), - "Use receiveAsync instead") - .def("receiveAsync3", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy3, (bp::arg("replyCallback")), - "Use receiveAsync instead") - .def("receiveAsync4", &SignalSlotableWrap::RequestorWrap::receiveAsyncPy4, (bp::arg("replyCallback")), - "Use receiveAsync instead"); - - bp::class_("AsyncReply", bp::no_init) - .def("__call__", &SignalSlotableWrap::AsyncReplyWrap::replyPy0, "Reply slot call without argument") - .def("__call__", &SignalSlotableWrap::AsyncReplyWrap::replyPy1, (bp::arg("a1")), - "Reply slot call with one argument") - .def("__call__", &SignalSlotableWrap::AsyncReplyWrap::replyPy2, (bp::arg("a1"), bp::arg("a2")), - "Reply slot call with two arguments") - .def("__call__", &SignalSlotableWrap::AsyncReplyWrap::replyPy3, (bp::arg("a1"), bp::arg("a2"), bp::arg("a3")), - "Reply slot call with three arguments") - .def("__call__", &SignalSlotableWrap::AsyncReplyWrap::replyPy4, - (bp::arg("a1"), bp::arg("a2"), bp::arg("a4"), bp::arg("a4")), "Reply slot call with four arguments") - .def("error", &SignalSlotableWrap::AsyncReply::error, (bp::arg("message"), bp::arg("details")), - "Reply failure of slot call stating an error message and details like the\n" - "stack trace from 'traceback.format_exc()'"); - - bp::class_("SignalSlotableIntern") - .def(bp::init()); - - bp::class_, bp::bases, - boost::noncopyable>("SignalSlotable") - .def(bp::init<>()) - .def(bp::init()) - .def(bp::init()) - .def(bp::init()) - .def(bp::init()) - - .def("create", &SignalSlotableWrap::create, - (bp::arg("instanceId"), bp::arg("connectionParameters") = karabo::util::Hash(), - bp::arg("heartbeatInterval") = 10, bp::arg("instanceInfo") = karabo::util::Hash()), - "\nUse this factory method to create SignalSlotable object with given 'instanceId', " - "'connectionParameters', 'heartbeatInterval' and 'instanceInfo'.\n" - "Example:\n\tss = SignalSlotable.create('a')\n") - .staticmethod("create") - - .def("start", &SignalSlotableWrap::start) - - .def("getSenderInfo", - (const boost::shared_ptr& (SignalSlotable::*)(const std::string&))( - &SignalSlotable::getSenderInfo), - bp::arg("slotFunction"), bp::return_value_policy()) - .def("getInstanceId", (bp::object(SignalSlotableWrap::*)()) & SignalSlotableWrap::getInstanceId) - .def("updateInstanceInfo", - (void(SignalSlotable::*)(const karabo::util::Hash&, bool))(&SignalSlotable::updateInstanceInfo), - (bp::arg("update"), bp::arg("remove") = false)) - .def("getInstanceInfo", - static_cast(&SignalSlotable::getInstanceInfo)) - .def("registerSlotCallGuardHandler", &SignalSlotableWrap::registerSlotCallGuardHandlerPy, - (bp::arg("handler"))) - - .def("registerPerformanceStatisticsHandler", &SignalSlotableWrap::registerPerformanceStatisticsHandlerPy, - (bp::arg("handler"))) - - .def("registerBrokerErrorHandler", &SignalSlotableWrap::registerBrokerErrorHandlerPy, (bp::arg("handler"))) - - .def("connect", &SignalSlotableWrap::connectPy, - (bp::arg("signalInstanceId"), bp::arg("signalFunction"), bp::arg("slotInstanceId"), - bp::arg("slotFunction")), - "\nUse this method to connect \"signalFunction\" issued by \"signalInstanceId\" with \"slotFunction\" " - "belonging to \"slotInstanceId\"" - "\n\nExample:\n\nIf we have to communicate with remote client registered as instance \"b\" and slot " - "\"onMoin\" ...\n\n\t" - "ss = SignalSlotable(\"a\")\n\tss.connect(\"\", \"moin\", \"b\", \"onMoin\")\n\tss.emit(\"moin\", 12)\n") - - .def("connect", &SignalSlotableWrap::connectPy_old, (bp::arg("signalFunction"), bp::arg("slotFunction"))) - - .def("getAvailableInstances", &SignalSlotableWrap::getAvailableInstancesPy, - (bp::arg("activateTracking") = false)) - .def("getAvailableSignals", &SignalSlotableWrap::getAvailableSignalsPy, bp::arg("instanceId")) - .def("getAvailableSlots", &SignalSlotableWrap::getAvailableSlotsPy, bp::arg("instanceId")) - - .def("disconnect", &SignalSlotable::disconnect, - (bp::arg("signalInstanceId"), bp::arg("signalFunction"), bp::arg("slotInstanceId"), - bp::arg("slotFunction"))) - .def("getInstanceId", (string const& (SignalSlotable::*)() const)(&SignalSlotable::getInstanceId), - bp::return_value_policy()) - - .def("registerSlot", (&SignalSlotableWrap::registerSlotPy), - (bp::arg("slotFunction"), bp::arg("slotName") = std::string(), bp::arg("numArgs") = -1), - "Register a callable as slot function.\n" - "If slotName empty (default), it is registered under slotFunction.__name__, else under slotName\n" - "If numArg < 0 (default), try to deduce number of arguments that the function should take\n" - " - that is known to work for functions and methods without '*args'. Otherwise use numArgs.") - - - .def("registerSignal", &SignalSlotableWrap::registerSignalPy<>, (bp::arg("signalFunction"))) - .def("registerSignal", &SignalSlotableWrap::registerSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"))) - .def("registerSignal", &SignalSlotableWrap::registerSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"))) - .def("registerSignal", &SignalSlotableWrap::registerSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("registerSignal", &SignalSlotableWrap::registerSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("registerSystemSignal", &SignalSlotableWrap::registerSystemSignalPy<>, (bp::arg("signalFunction"))) - .def("registerSystemSignal", &SignalSlotableWrap::registerSystemSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"))) - .def("registerSystemSignal", &SignalSlotableWrap::registerSystemSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"))) - .def("registerSystemSignal", &SignalSlotableWrap::registerSystemSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("registerSystemSignal", - &SignalSlotableWrap::registerSystemSignalPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("emit", &SignalSlotableWrap::emitPy<>, (bp::arg("signalFunction"))) - .def("emit", &SignalSlotableWrap::emitPy, (bp::arg("signalFunction"), bp::arg("a1"))) - .def("emit", &SignalSlotableWrap::emitPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"))) - .def("emit", &SignalSlotableWrap::emitPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("emit", &SignalSlotableWrap::emitPy, - (bp::arg("signalFunction"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("call", &SignalSlotableWrap::callPy<>, (bp::arg("instanceId"), bp::arg("slotName"))) - .def("call", &SignalSlotableWrap::callPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"))) - .def("call", &SignalSlotableWrap::callPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"))) - .def("call", &SignalSlotableWrap::callPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("call", &SignalSlotableWrap::callPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("request", &SignalSlotableWrap::requestPy<>, (bp::arg("instanceId"), bp::arg("slotName"))) - .def("request", &SignalSlotableWrap::requestPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"))) - .def("request", &SignalSlotableWrap::requestPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"))) - .def("request", &SignalSlotableWrap::requestPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("request", &SignalSlotableWrap::requestPy, - (bp::arg("instanceId"), bp::arg("slotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("requestNoWait", &SignalSlotableWrap::requestNoWaitPy<>, - (bp::arg("requestInstanceId"), bp::arg("requestSlotName"), bp::arg("replyInstanceId"), - bp::arg("replySlotName"))) - .def("requestNoWait", &SignalSlotableWrap::requestNoWaitPy, - (bp::arg("requestInstanceId"), bp::arg("requestSlotName"), bp::arg("replyInstanceId"), - bp::arg("replySlotName"), bp::arg("a1"))) - .def("requestNoWait", &SignalSlotableWrap::requestNoWaitPy, - (bp::arg("requestInstanceId"), bp::arg("requestSlotName"), bp::arg("replyInstanceId"), - bp::arg("replySlotName"), bp::arg("a1"), bp::arg("a2"))) - .def("requestNoWait", &SignalSlotableWrap::requestNoWaitPy, - (bp::arg("requestInstanceId"), bp::arg("requestSlotName"), bp::arg("replyInstanceId"), - bp::arg("replySlotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("requestNoWait", &SignalSlotableWrap::requestNoWaitPy, - (bp::arg("requestInstanceId"), bp::arg("requestSlotName"), bp::arg("replyInstanceId"), - bp::arg("replySlotName"), bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("reply", &SignalSlotableWrap::replyPy<>) - .def("reply", &SignalSlotableWrap::replyPy, (bp::arg("a1"))) - .def("reply", &SignalSlotableWrap::replyPy, (bp::arg("a1"), bp::arg("a2"))) - .def("reply", &SignalSlotableWrap::replyPy, - (bp::arg("a1"), bp::arg("a2"), bp::arg("a3"))) - .def("reply", &SignalSlotableWrap::replyPy, - (bp::arg("a1"), bp::arg("a2"), bp::arg("a3"), bp::arg("a4"))) - - .def("createAsyncReply", &SignalSlotableWrap::createAsyncReply, - "Create an AsyncReply to postpone the reply of a slot.\n\n" - "Only call within a slot call - and then take care to use the AsyncReply to\n" - "either reply or report an error since no automatic reply will happen.") - - .def("createOutputChannel", &SignalSlotableWrap::createOutputChannelPy, - (bp::arg("channelName"), bp::arg("configuration"), bp::arg("handler") = bp::object())) - - .def("createInputChannel", &SignalSlotableWrap::createInputChannelPy, - (bp::arg("channelName"), bp::arg("configuration"), bp::arg("onData") = bp::object(), - bp::arg("onInput") = bp::object(), bp::arg("onEndOfStream") = bp::object(), - bp::arg("connectionTracker") = bp::object())) - - .def("connectInputChannels", &SignalSlotableWrap::connectInputChannelsPy) - - .def("getOutputChannel", &SignalSlotableWrap::getOutputChannelPy, (bp::arg("channelName"))) - - .def("getInputChannel", &SignalSlotableWrap::getInputChannelPy, (bp::arg("channelName"))) - - .def("getOutputChannelNames", &SignalSlotable::getOutputChannelNames) - - .def("getInputChannelNames", &SignalSlotableWrap::getInputChannelNamesPy) - - .def("removeInputChannel", &SignalSlotable::removeInputChannel, (bp::arg("channelName"))) - - .def("removeOutputChannel", &SignalSlotable::removeOutputChannel, (bp::arg("channelName"))) - - .def("registerDataHandler", &SignalSlotableWrap::registerDataHandlerPy, - (bp::arg("channelName"), bp::arg("handlerPerData") = bp::object())) - - .def("registerInputHandler", &SignalSlotableWrap::registerInputHandlerPy, - (bp::arg("channelName"), bp::arg("handlerPerInput") = bp::object())) - - .def("registerEndOfStreamHandler", &SignalSlotableWrap::registerEndOfStreamHandlerPy, - (bp::arg("channelName"), bp::arg("handler") = bp::object())) - - .def("exists", (bp::tuple(SignalSlotableWrap::*)(const std::string&))(&SignalSlotableWrap::existsPy), - (bp::arg("instanceId"))) - .def("getConnection", &SignalSlotable::getConnection) - .def("getTopic", &SignalSlotable::getTopic, bp::return_value_policy()); -} diff --git a/src/karathon/PyXmsSlotElement.cc b/src/karathon/PyXmsSlotElement.cc deleted file mode 100644 index 852ea9870f..0000000000 --- a/src/karathon/PyXmsSlotElement.cc +++ /dev/null @@ -1,155 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include - -#include "PythonMacros.hh" -#include "boost/python.hpp" -#include "boost/python/raw_function.hpp" - - -namespace bp = boost::python; -using namespace karabo::xms; -using namespace karabo::util; -using namespace std; - - -struct SlotElementBase_Wrapper : SlotElementBase, bp::wrapper > { - SlotElementBase_Wrapper(Schema& expected) - : SlotElementBase(boost::ref(expected)), bp::wrapper >() {} - - - virtual void commit() { - bp::override func_commit = this->get_override("commit"); - func_commit(); - } - - - virtual void beforeAddition() { - bp::override func_beforeAddition = this->get_override("beforeAddition"); - func_beforeAddition(); - } -}; - - -struct SLOT_ELEMENT_Wrapper : SLOT_ELEMENT, bp::wrapper { - SLOT_ELEMENT_Wrapper(SLOT_ELEMENT const& arg) : SLOT_ELEMENT(arg), bp::wrapper() {} - - - SLOT_ELEMENT_Wrapper(Schema& expected) : SLOT_ELEMENT(boost::ref(expected)), bp::wrapper() {} - - - virtual void commit() { - if (bp::override func_commit = this->get_override("commit")) func_commit(); - else this->SLOT_ELEMENT::commit(); - } - - - void default_commit() { - SLOT_ELEMENT::commit(); - } -}; - - -class SlotElementWrap { - public: - static bp::object allowedStatesPy(bp::tuple args, bp::dict kwargs) { - std::vector states; - SLOT_ELEMENT& self = bp::extract(args[0]); - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } - self.allowedStates(states); - return args[0]; - } -}; - - -void exportPyXmsSlotElement() { - bp::class_ sl("SlotElementBase", - bp::init(bp::arg("expected"))); - - sl.def("allowedStates", bp::raw_function(&SlotElementWrap::allowedStatesPy, 2)); - - sl.def("commit", - bp::pure_virtual((void(SlotElementBase::*)())(&SlotElementBase::commit)), - bp::return_internal_reference<>()); - - sl.def("description", - (SLOT_ELEMENT & - (SlotElementBase::*)(string const&))(&SlotElementBase::description), - (bp::arg("desc")), bp::return_internal_reference<>()); - - sl.def("displayedName", - (SLOT_ELEMENT & - (SlotElementBase::*)(string const&))(&SlotElementBase::displayedName), - (bp::arg("displayedName")), bp::return_internal_reference<>()); - - sl.def("key", - (SLOT_ELEMENT & (SlotElementBase::*)(string const&))(&SlotElementBase::key), - (bp::arg("name")), bp::return_internal_reference<>()); - - sl.def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()); - - sl.def("tags", - (SLOT_ELEMENT & - (SlotElementBase::*)(string const&, string const&))(&SlotElementBase::tags), - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()); - - sl.def("tags", - (SLOT_ELEMENT & - (SlotElementBase::*)(vector const&))(&SlotElementBase::tags), - (bp::arg("tags")), bp::return_internal_reference<>()); - - sl.def("observerAccess", - (SLOT_ELEMENT & (SlotElementBase::*)())(&SlotElementBase::observerAccess), - bp::return_internal_reference<>()); - - sl.def("userAccess", - (SLOT_ELEMENT & (SlotElementBase::*)())(&SlotElementBase::userAccess), - bp::return_internal_reference<>()); - - sl.def("operatorAccess", - (SLOT_ELEMENT & (SlotElementBase::*)())(&SlotElementBase::operatorAccess), - bp::return_internal_reference<>()); - - sl.def("expertAccess", - (SLOT_ELEMENT & (SlotElementBase::*)())(&SlotElementBase::expertAccess), - bp::return_internal_reference<>()); - - sl.def("adminAccess", - (SLOT_ELEMENT & (SlotElementBase::*)())(&SlotElementBase::adminAccess), - bp::return_internal_reference<>()); - - { // karabo::xms::SLOT_ELEMENT - bp::class_ > > elem( - "SLOT_ELEMENT", bp::init(bp::arg("expected"))); - - bp::implicitly_convertible(); - - elem.def("commit", (void(SLOT_ELEMENT::*)())(&SLOT_ELEMENT::commit), - (void(SLOT_ELEMENT_Wrapper::*)())(&SLOT_ELEMENT_Wrapper::default_commit)); - } -} diff --git a/src/karathon/PythonFactoryMacros.hh b/src/karathon/PythonFactoryMacros.hh deleted file mode 100644 index 3e5be7d71e..0000000000 --- a/src/karathon/PythonFactoryMacros.hh +++ /dev/null @@ -1,97 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef PYTHONFACTORYMACROS_HH -#define PYTHONFACTORYMACROS_HH - -#include - -namespace bp = boost::python; - -#define KARABO_PYTHON_FACTORY_CONFIGURATOR(baseClass) \ - .def("classInfo", (karabo::util::ClassInfo(*)())(&karabo::util::Configurator::classInfo), \ - "Returns C++ introspection info for \"" #baseClass "\"") \ - .staticmethod("classInfo") \ - .def("create", \ - (boost::shared_ptr(*)(karabo::util::Hash const&, bool const))( \ - &karabo::util::Configurator::create), \ - (bp::arg("input"), bp::arg("validate") = (bool const)(true)), \ - "The factory method to create instance of C++ class derived from C++ base class \"" #baseClass \ - "\" using \"input\" configuration. The configuration should have \"classId\" of class to be " \ - "created\nas a root element. The last argument is a flag to " \ - "determine if the input configuration should be validated.") \ - .def("create", \ - (boost::shared_ptr(*)(std::string const&, karabo::util::Hash const&, bool const))( \ - &karabo::util::Configurator::create), \ - (bp::arg("classId"), bp::arg("input") = karabo::util::Hash(), \ - bp::arg("validate") = (bool const)(true)), \ - "The factory method to create the instance of C++ class with \"classId\" derived from C++ base class " \ - "\"" #baseClass \ - "\" using \"input\" configuration.\n" \ - "The last argument is a flag to determine if the input configuration should be validated.") \ - .staticmethod("create") \ - .def("createNode", \ - (boost::shared_ptr(*)(const std::string&, std::string const&, karabo::util::Hash const&, \ - bool const))(&karabo::util::Configurator::createNode), \ - (bp::arg("nodeName"), bp::arg("classId"), bp::arg("input") = karabo::util::Hash(), \ - bp::arg("validate") = (bool const)(true)), \ - "The factory method to create the instance of C++ class with \"classId\" derived from C++ base class " \ - "\"" #baseClass \ - "\" using \"input\" configuration.\n" \ - "The last argument is a flag to determine if the input configuration should be validated.") \ - .staticmethod("createNode") \ - .def("createChoice", \ - (boost::shared_ptr(*)(std::string const&, karabo::util::Hash const&, bool const))( \ - &karabo::util::Configurator::createChoice), \ - (bp::arg("choiceName"), bp::arg("input") = karabo::util::Hash(), \ - bp::arg("validate") = (bool const)(true)), \ - "The factory method to create the instance of C++ class with \"classId\" derived from C++ base class " \ - "\"" #baseClass \ - "\" using \"input\" configuration.\n" \ - "The last argument is a flag to determine if the input configuration should be validated.") \ - .staticmethod("createChoice") \ - .def("createList", \ - (boost::shared_ptr(*)(std::string const&, karabo::util::Hash const&, bool const))( \ - &karabo::util::Configurator::createList), \ - (bp::arg("listName"), bp::arg("input") = karabo::util::Hash(), \ - bp::arg("validate") = (bool const)(true)), \ - "The factory method to create the instance of C++ class with \"classId\" derived from C++ base class " \ - "\"" #baseClass \ - "\" using \"input\" configuration.\n" \ - "The last argument is a flag to determine if the input configuration should be validated.") \ - .staticmethod("createList") \ - .def("getClassInfo", (karabo::util::ClassInfo(karabo::util::Configurator::*)() \ - const)(&karabo::util::Configurator::getClassInfo)) \ - .def("getRegisteredClasses", \ - (std::vector(*)())(&karabo::util::Configurator::getRegisteredClasses), \ - "Get list of classIds of all C++ classes derived from given C++ base class \"" #baseClass "\".") \ - .staticmethod("getRegisteredClasses") \ - .def("getSchema", \ - (karabo::util::Schema(*)(std::string const&, karabo::util::Schema::AssemblyRules const&))( \ - &karabo::util::Configurator::getSchema), \ - (bp::arg("classId"), bp::arg("rules") = karabo::util::Schema::AssemblyRules()), \ - "Get schema for C++ class with \"classId\" derived from C++ base class \"" #baseClass \ - "\" using assembly \"rules\"") \ - .staticmethod("getSchema") \ - .attr("__karabo_cpp_classid__") = baseClass::classInfo().getClassId() - -#endif /* PYTHONFACTORYMACROS_HH */ diff --git a/src/karathon/PythonInputHandler.cc b/src/karathon/PythonInputHandler.cc deleted file mode 100644 index 98dc506b66..0000000000 --- a/src/karathon/PythonInputHandler.cc +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include "PythonInputHandler.hh" - -#include - -KARABO_REGISTER_IN_FACTORY_1(karabo::io::InputHandler, - karathon::PythonInputHandler >, - karabo::io::AbstractInput::Pointer); - -KARABO_REGISTER_IN_FACTORY_1(karabo::io::InputHandler, - karathon::PythonInputHandler > >, - karabo::io::AbstractInput::Pointer); diff --git a/src/karathon/PythonInputHandler.hh b/src/karathon/PythonInputHandler.hh deleted file mode 100644 index d74e4ed0c8..0000000000 --- a/src/karathon/PythonInputHandler.hh +++ /dev/null @@ -1,97 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: PythonInputHandler.hh - * Author: esenov - * - * Created on September 17, 2013, 5:37 PM - */ - -#ifndef KARATHON_PYTHONINPUTHANDLER_HH -#define KARATHON_PYTHONINPUTHANDLER_HH - -#include -#include -#include -#include -#include - -#include "ScopedGILAcquire.hh" -#include "Wrapper.hh" - -namespace bp = boost::python; - -namespace karathon { - - template - class PythonInputHandler : public karabo::io::InputHandler { - public: - KARABO_CLASSINFO(PythonInputHandler, "PythonInputHandler" + std::string(typeid(InputType).name()), "1.0") - - PythonInputHandler() {} - - PythonInputHandler(const karabo::io::AbstractInput::Pointer& input) - : m_input(boost::static_pointer_cast(input)) {} - - virtual ~PythonInputHandler() {} - - void registerIOEventHandler(const boost::any& ioEventHandler) { - bp::object handler = boost::any_cast(ioEventHandler); - if (handler == bp::object()) { - m_ioEventHandler = bp::object(); - return; - } - // Check if input handler is a python function at least - if (!Wrapper::hasattr(handler, "__name__")) { - throw KARABO_PYTHON_EXCEPTION("This python object is not a function."); - } - m_ioEventHandler = handler; - } - - void registerEndOfStreamEventHandler(const boost::any& endOfStreamEventHandler) { - bp::object handler = boost::any_cast(endOfStreamEventHandler); - if (handler == bp::object()) { - m_endOfStreamEventHandler = bp::object(); - return; - } - if (!Wrapper::hasattr(handler, "__name__")) { - throw KARABO_PYTHON_EXCEPTION("This python object is not a function."); - } - m_endOfStreamEventHandler = handler; - } - - void triggerIOEvent() { - ScopedGILAcquire gil; - if (m_ioEventHandler != bp::object()) { - if (typename InputType::Pointer in = m_input.lock()) m_ioEventHandler(bp::object(in)); - } - } - - void triggerEndOfStreamEvent() { - ScopedGILAcquire gil; - if (m_endOfStreamEventHandler != bp::object()) m_endOfStreamEventHandler(); - } - - private: - boost::weak_ptr m_input; - bp::object m_ioEventHandler; - bp::object m_endOfStreamEventHandler; - }; -} // namespace karathon - -#endif /* KARATHON_PYTHONINPUTHANDLER_HH */ diff --git a/src/karathon/PythonMacros.hh b/src/karathon/PythonMacros.hh deleted file mode 100644 index 7b455f0d54..0000000000 --- a/src/karathon/PythonMacros.hh +++ /dev/null @@ -1,536 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef KARATHON_MACROSFORPYTHON_HH -#define KARATHON_MACROSFORPYTHON_HH - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Wrapper.hh" - - -namespace bp = boost::python; - -template -struct AliasAttributeWrap { - static T& aliasPy(T& self, const bp::object& obj) { - if (PyLong_Check(obj.ptr())) { - int param = bp::extract(obj); - return self.alias(param); - } else if (PyUnicode_Check(obj.ptr())) { - std::string param = bp::extract(obj); - return self.alias(param); - } else if (PyFloat_Check(obj.ptr())) { - double param = bp::extract(obj); - return self.alias(param); - } else if (PyList_Check(obj.ptr())) { - bp::ssize_t size = bp::len(obj); - if (size == 0) { - std::vector params = std::vector(); - return self.alias(params); - } - bp::object list0 = obj[0]; - if (list0.ptr() == Py_None) { - std::vector v; - for (bp::ssize_t i = 0; i < size; ++i) v.push_back(karabo::util::CppNone()); - return self.alias(v); - } - if (PyBool_Check(list0.ptr())) { - std::vector v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return self.alias(v); - } - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return self.alias(v); - } - if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return self.alias(v); - } - // XXX: Whoa! This check was already performed! -JW 14.7.2016 - if (PyLong_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return self.alias(v); - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - return self.alias(v); - } - // XXX: Whoa! This check was ALSO already performed! -JW 14.7.2016 - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - bp::object str(bp::handle<>(PyUnicode_AsUTF8String(static_cast(obj[i]).ptr()))); - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(str.ptr(), &size); - v[i] = std::string(data, size); - } - return self.alias(v); - } - } - throw KARABO_PYTHON_EXCEPTION("Unknown data type of the 'alias' element"); - } -}; - -template -struct DefaultValueVectorWrap { - typedef std::vector VType; - typedef karabo::util::VectorElement U; - typedef karabo::util::DefaultValue DefValueVec; - - static U& defaultValue(DefValueVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.defaultValue(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the defaultValue of VectorElement must be a list"); - } - } -}; - -struct DefaultValueTableWrap { - typedef std::vector VType; - typedef karabo::util::TableElement U; - typedef karabo::util::TableDefaultValue DefValueVec; - - static U& defaultValue(DefValueVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.defaultValue(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the defaultValue of TableElement must be a list"); - } - } -}; - -template -struct ReadOnlySpecificVectorWrap { - typedef std::vector VType; - typedef karabo::util::VectorElement U; - typedef karabo::util::ReadOnlySpecific ReadOnlySpecVec; - typedef karabo::util::AlarmSpecific AlarmSpecVec; - - static ReadOnlySpecVec& initialValue(ReadOnlySpecVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.initialValue(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the initialValue of VectorElement must be a list"); - } - } - - static AlarmSpecVec warnLowValue(ReadOnlySpecVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.warnLow(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the warnLow value of VectorElement must be a list"); - } - } - - static AlarmSpecVec warnHighValue(ReadOnlySpecVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.warnHigh(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the warnHigh value of VectorElement must be a list"); - } - } - - static AlarmSpecVec alarmLowValue(ReadOnlySpecVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.alarmLow(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the alarmLow value of VectorElement must be a list"); - } - } - - static AlarmSpecVec alarmHighValue(ReadOnlySpecVec& self, const bp::object& obj) { - if (PyList_Check(obj.ptr())) { - VType v = karathon::Wrapper::fromPyListToStdVector(obj); - return self.alarmHigh(v); - } else { - throw KARABO_PYTHON_EXCEPTION("Python type of the alarmHigh value of VectorElement must be a list"); - } - } -}; - -struct NDArrayElementWrap { - static karabo::util::NDArrayElement& dtype(karabo::util::NDArrayElement& self, const bp::object& obj) { - using namespace karabo::util; - Types::ReferenceType reftype = Types::UNKNOWN; - - if (bp::extract(obj).check()) { - std::string type = bp::extract(obj); - reftype = Types::from(type); - } else if (bp::extract(obj).check()) { - karathon::PyTypes::ReferenceType type = bp::extract(obj); - reftype = karathon::PyTypes::to(type); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of dtype of NDArrayElement must be a string or Types enumerated value."); - } - return self.dtype(reftype); - } - - static karabo::util::NDArrayElement& shape(karabo::util::NDArrayElement& self, const bp::object& obj) { - if (PyUnicode_Check(obj.ptr())) { - return self.shape(bp::extract(obj)); - } else if (PyList_Check(obj.ptr())) { - const std::vector v = karathon::Wrapper::fromPyListToStdVector(obj); - const std::string shapeStr = karabo::util::toString(v); - return self.shape(shapeStr); - } else { - throw KARABO_PYTHON_EXCEPTION( - "Python type of the shape value of NDArrayElement must be a list or a string"); - } - } -}; - - -/////////////////////////////////////////////////////////////////////////// -// DefaultValue > where EType: -// BOOL, INT32, UINT32, INT64, UINT64, STRING, DOUBLE -#define KARABO_PYTHON_ELEMENT_DEFAULT_VALUE(U, EType, e) \ - { \ - typedef DefaultValue DefValue; \ - bp::class_("DefaultValue" #e, bp::no_init) \ - .def("defaultValue", (U & (DefValue::*)(EType const&))(&DefValue::defaultValue), \ - (bp::arg("defaultValue")), bp::return_internal_reference<>()) \ - .def("defaultValueFromString", \ - (U & (DefValue::*)(std::string const&))(&DefValue::defaultValueFromString), \ - (bp::arg("defaultValue")), bp::return_internal_reference<>()) \ - .def("noDefaultValue", (U & (DefValue::*)())(&DefValue::noDefaultValue), \ - bp::return_internal_reference<>()); \ - } - -/////////////////////////////////////////////////////////////////////////// -// DefaultValue, std::vector > -#define KARABO_PYTHON_VECTOR_DEFAULT_VALUE(T, e) \ - { \ - typedef std::vector VType; \ - typedef karabo::util::VectorElement U; \ - typedef karabo::util::DefaultValue DefValueVec; \ - bp::class_("DefaultValueVector" #e, bp::no_init) \ - .def("defaultValue", &DefaultValueVectorWrap::defaultValue, (bp::arg("self"), bp::arg("pyList")), \ - bp::return_internal_reference<>()) \ - .def("defaultValueFromString", \ - (U & (DefValueVec::*)(std::string const&))(&DefValueVec::defaultValueFromString), \ - (bp::arg("defaultValueString")), bp::return_internal_reference<>()) \ - .def("noDefaultValue", (U & (DefValueVec::*)())(&DefValueVec::noDefaultValue), \ - bp::return_internal_reference<>()); \ - } - -///////////////////////////////////////////////////////////// -#define KARABO_PYTHON_ELEMENT_ALARMSPECIFIC(U, EType, Rtype, e) \ - { \ - typedef Rtype ReturnSpec; \ - typedef AlarmSpecific AlarmSpec; \ - bp::class_("AlarmSpecific" #e #Rtype, bp::no_init) \ - .def("needsAcknowledging", (ReturnSpec & (AlarmSpec::*)(const bool))(&AlarmSpec::needsAcknowledging), \ - bp::return_internal_reference<>()) \ - .def("info", (AlarmSpec & (AlarmSpec::*)(const std::string&))(&AlarmSpec::info), \ - bp::return_internal_reference<>()); \ - } - - -///////////////////////////////////////////////////////////// -#define KARABO_PYTHON_ELEMENT_ROLLINGSTATSPECIFIC(U, EType, e) \ - { \ - typedef ReadOnlySpecific ReadOnlySpec; \ - typedef RollingStatsSpecific RollingStatsSpec; \ - typedef AlarmSpecific AlarmSpec; \ - bp::class_("RollingStatsSpecific" #e, bp::no_init) \ - .def("evaluationInterval", \ - (ReadOnlySpec & (RollingStatsSpec::*)(const unsigned int))(&RollingStatsSpec::evaluationInterval), \ - bp::return_internal_reference<>()); \ - } - -///////////////////////////////////////////////////////////// -#define KARABO_PYTHON_ELEMENT_READONLYSPECIFIC(U, EType, e) \ - { \ - typedef ReadOnlySpecific ReadOnlySpec; \ - typedef AlarmSpecific AlarmSpec; \ - typedef RollingStatsSpecific RollingStatsSpec; \ - bp::class_("ReadOnlySpecific" #e, bp::no_init) \ - .def("alarmHigh", (AlarmSpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::alarmHigh), \ - bp::return_internal_reference<>()) \ - .def("alarmLow", (AlarmSpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::alarmLow), \ - bp::return_internal_reference<>()) \ - .def("warnHigh", (AlarmSpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::warnHigh), \ - bp::return_internal_reference<>()) \ - .def("warnLow", (AlarmSpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::warnLow), \ - bp::return_internal_reference<>()) \ - .def("enableRollingStats", &ReadOnlySpec::enableRollingStats, bp::return_internal_reference<>()) \ - .def("initialValueFromString", \ - (ReadOnlySpec & (ReadOnlySpec::*)(std::string const&))(&ReadOnlySpec::initialValueFromString), \ - bp::return_internal_reference<>()) \ - .def("initialValue", (ReadOnlySpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::initialValue), \ - bp::return_internal_reference<>()) \ - .def("defaultValue", (ReadOnlySpec & (ReadOnlySpec::*)(EType const&))(&ReadOnlySpec::initialValue), \ - bp::return_internal_reference<>()) \ - .def("archivePolicy", \ - (ReadOnlySpec & \ - (ReadOnlySpec::*)(karabo::util::Schema::ArchivePolicy const&))(&ReadOnlySpec::archivePolicy), \ - bp::return_internal_reference<>()) \ - .def("commit", (void(ReadOnlySpec::*)())(&ReadOnlySpec::commit)); \ - } - -///////////////////////////////////////////////////////////// -#define KARABO_PYTHON_VECTOR_READONLYSPECIFIC(T, e) \ - { \ - typedef std::vector VType; \ - typedef karabo::util::VectorElement U; \ - typedef karabo::util::ReadOnlySpecific ReadOnlySpecVec; \ - typedef karabo::util::AlarmSpecific AlarmSpecVec; \ - typedef RollingStatsSpecific RollingStatsSpecArr; \ - bp::class_("ReadOnlySpecificVector" #e, bp::no_init) \ - .def("initialValue", &ReadOnlySpecificVectorWrap::initialValue, (bp::arg("self"), bp::arg("pyList")), \ - bp::return_internal_reference<>()) \ - .def("defaultValue", &ReadOnlySpecificVectorWrap::initialValue, (bp::arg("self"), bp::arg("pyList")), \ - bp::return_internal_reference<>()) \ - .def("alarmHigh", &ReadOnlySpecificVectorWrap::alarmHighValue, (bp::arg("self"), bp::arg("pyList"))) \ - .def("alarmLow", &ReadOnlySpecificVectorWrap::alarmLowValue, (bp::arg("self"), bp::arg("pyList"))) \ - .def("warnHigh", &ReadOnlySpecificVectorWrap::warnHighValue, (bp::arg("self"), bp::arg("pyList"))) \ - .def("warnLow", &ReadOnlySpecificVectorWrap::warnLowValue, (bp::arg("self"), bp::arg("pyList"))) \ - .def("enableRollingStats", (RollingStatsSpecArr(ReadOnlySpecVec::*)(std::string const&))( \ - &ReadOnlySpecVec::enableRollingStats)) \ - .def("initialValueFromString", \ - (ReadOnlySpecVec & \ - (ReadOnlySpecVec::*)(std::string const&))(&ReadOnlySpecVec::initialValueFromString), \ - bp::return_internal_reference<>()) \ - .def("archivePolicy", \ - (ReadOnlySpecVec & (ReadOnlySpecVec::*)(karabo::util::Schema::ArchivePolicy const&))( \ - &ReadOnlySpecVec::archivePolicy), \ - bp::return_internal_reference<>()) \ - .def("commit", (void(ReadOnlySpecVec::*)())(&ReadOnlySpecVec::commit)); \ - } - -/** - * The following macro KARABO_PYTHON_SIMPLE - * is used for python binding of - * @code - * karabo::util::SimpleElement< EType > - * @endcode - * where EType: int, long long, double. - * In Python: INT32_ELEMENT, ..UINT32.., INT64_ELEMENT, ..UINT64.., - * DOUBLE_ELEMENT, STRING_ELEMENT, BOOL_ELEMENT - * - */ -#define KARABO_PYTHON_SIMPLE(t, e) \ - { \ - typedef t EType; \ - typedef SimpleElement T; \ - bp::implicitly_convertible(); \ - bp::class_(#e "_ELEMENT", bp::init((bp::arg("expected")))) \ - KARABO_PYTHON_COMMON_ATTRIBUTES(T) KARABO_PYTHON_OPTIONS_NONVECTOR(T) \ - KARABO_PYTHON_NUMERIC_ATTRIBUTES(T); \ - } - -template -class CommonWrap { - public: - static bp::object allowedStatesPy(bp::tuple args, bp::dict kwargs) { - T& self = bp::extract(args[0]); - std::vector states; - for (unsigned int i = 1; i < bp::len(args); ++i) { - const std::string state = bp::extract(args[i].attr("name")); - states.push_back(karabo::util::State::fromString(state)); - } - self.allowedStates(states); - return args[0]; - } -}; - -#define KARABO_PYTHON_COMMON_ATTRIBUTES(T) \ - .def("observerAccess", &T::observerAccess, bp::return_internal_reference<>()) \ - .def("userAccess", &T::userAccess, bp::return_internal_reference<>()) \ - .def("operatorAccess", &T::operatorAccess, bp::return_internal_reference<>()) \ - .def("expertAccess", &T::expertAccess, bp::return_internal_reference<>()) \ - .def("adminAccess", &T::adminAccess, bp::return_internal_reference<>()) \ - .def("allowedStates", bp::raw_function(&CommonWrap::allowedStatesPy, 2)) \ - .def("assignmentInternal", &T::assignmentInternal, bp::return_internal_reference<>()) \ - .def("assignmentMandatory", &T::assignmentMandatory, bp::return_internal_reference<>()) \ - .def("assignmentOptional", &T::assignmentOptional, bp::return_internal_reference<>()) \ - .def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()) \ - .def("commit", &T::commit, bp::return_internal_reference<>()) \ - .def("commit", (T & (T::*)(karabo::util::Schema&))(&T::commit), bp::arg("expected"), \ - bp::return_internal_reference<>()) \ - .def("description", &T::description, bp::return_internal_reference<>()) \ - .def("displayedName", &T::displayedName, bp::return_internal_reference<>()) \ - .def("unit", &T::unit, bp::return_internal_reference<>()) \ - .def("metricPrefix", &T::metricPrefix, bp::return_internal_reference<>()) \ - .def("init", &T::init, bp::return_internal_reference<>()) \ - .def("key", &T::key, bp::return_internal_reference<>()) \ - .def("setSpecialDisplayType", (T & (T::*)(std::string const&))(&T::setSpecialDisplayType), \ - bp::arg("displayType"), bp::return_internal_reference<>()) \ - .def("readOnly", &T::readOnly, bp::return_internal_reference<>()) \ - .def("reconfigurable", &T::reconfigurable, bp::return_internal_reference<>()) \ - .def("tags", (T & (T::*)(std::string const&, std::string const&))(&T::tags), \ - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) \ - .def("tags", (T & (T::*)(std::vector const&))(&T::tags), (bp::arg("tags")), \ - bp::return_internal_reference<>()) \ - .def("daqPolicy", (T & (T::*)(karabo::util::DAQPolicy const&))(&T::daqPolicy), (bp::arg("daqPolicy")), \ - bp::return_internal_reference<>()) - - -#define KARABO_PYTHON_OPTIONS_NONVECTOR(T) \ - .def("options", (T & (T::*)(std::string const&, std::string const&))(&T::options), \ - (bp::arg("opts"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) \ - .def("options", (T & (T::*)(std::vector const&))(&T::options), (bp::arg("opts")), \ - bp::return_internal_reference<>()) - - -#define KARABO_PYTHON_NUMERIC_ATTRIBUTES(T) \ - .def("hex", &T::hex, bp::return_internal_reference<>()) \ - .def("oct", &T::oct, bp::return_internal_reference<>()) \ - .def("bin", (T & (T::*)()) & T::bin, bp::return_internal_reference<>()) \ - .def("bin", (T & (T::*)(const std::string&)) & T::bin, (bp::arg("meaning")), \ - bp::return_internal_reference<>()) \ - .def("maxExc", &T::maxExc, bp::return_internal_reference<>()) \ - .def("maxInc", &T::maxInc, bp::return_internal_reference<>()) \ - .def("minExc", &T::minExc, bp::return_internal_reference<>()) \ - .def("minInc", &T::minInc, bp::return_internal_reference<>()) - - -/** - * The following macro KARABO_PYTHON_VECTOR is used for python binding of - * @code - * karabo::util::VectorElement< EType, std::vector > - * @endcode - * where EType: int, long long, double. - * In Python: VECTOR_INT32_ELEMENT, ..UINT32.., VECTOR_INT64_ELEMENT, ..UINT64.., - * VECTOR_DOUBLE_ELEMENT, VECTOR_STRING_ELEMENT, VECTOR_BOOL_ELEMENT. - * - */ -#define KARABO_PYTHON_VECTOR(t, e) \ - { \ - typedef t EType; \ - typedef VectorElement T; \ - bp::implicitly_convertible(); \ - bp::class_("VECTOR_" #e "_ELEMENT", \ - bp::init((bp::arg("expected")))) \ - KARABO_PYTHON_COMMON_ATTRIBUTES(T) \ - .def("maxSize", (T & (T::*)(int const&))(&T::maxSize), bp::return_internal_reference<>()) \ - .def("minSize", (T & (T::*)(int const&))(&T::minSize), bp::return_internal_reference<>()); \ - } - - -/** - * The following macro KARABO_PYTHON_NODE_CHOICE_LIST is used for python binding of - * @code - * karabo::util::NodeElement, karabo::util::ListElement, karabo::util::ChoiceElement - * @endcode - * - * In Python: NODE_ELEMENT, CHOICE_ELEMENT, LIST_ELEMENT - * - */ -#define KARABO_PYTHON_NODE_CHOICE_LIST(NameElem) \ - .def("observerAccess", &NameElem::observerAccess, bp::return_internal_reference<>()) \ - .def("userAccess", &NameElem::userAccess, bp::return_internal_reference<>()) \ - .def("operatorAccess", &NameElem::operatorAccess, bp::return_internal_reference<>()) \ - .def("expertAccess", &NameElem::expertAccess, bp::return_internal_reference<>()) \ - .def("adminAccess", &NameElem::adminAccess, bp::return_internal_reference<>()) \ - .def("key", &NameElem::key, bp::return_internal_reference<>()) \ - .def("description", &NameElem::description, bp::return_internal_reference<>()) \ - .def("displayedName", &NameElem::displayedName, bp::return_internal_reference<>()) \ - .def("alias", &AliasAttributeWrap::aliasPy, bp::return_internal_reference<>()) \ - .def("tags", (NameElem & (NameElem::*)(std::string const&, std::string const&))(&NameElem::tags), \ - (bp::arg("tags"), bp::arg("sep") = " ,;"), bp::return_internal_reference<>()) \ - .def("tags", (NameElem & (NameElem::*)(std::vector const&))(&NameElem::tags), \ - (bp::arg("tags")), bp::return_internal_reference<>()) \ - .def("commit", &NameElem::commit, bp::return_internal_reference<>()) \ - .def("commit", (NameElem & (NameElem::*)(karabo::util::Schema&))(&NameElem::commit), bp::arg("expected"), \ - bp::return_internal_reference<>()) - - -// Macro KARABO_PYTHON_ANY_EXTRACT is used in pyexfel.cc and pyexfelportable.cc for binding. -// Extracting boost.python object with correct data type from boost::any -#define KARABO_PYTHON_ANY_EXTRACT(t) \ - if (self.type() == typeid(t)) { \ - return boost::python::object(boost::any_cast(self)); \ - } \ - if (self.type() == typeid(std::vector)) { \ - typedef std::vector VContainer; \ - VContainer container(boost::any_cast(self)); \ - std::string str; \ - str.append("["); \ - for (size_t i = 0; i < container.size(); i++) { \ - std::stringstream tmp; \ - tmp << container[i]; \ - str.append(tmp.str()); \ - if (i < container.size() - 1) str.append(","); \ - } \ - str.append("]"); \ - return boost::python::object(str); \ - } - -/** - * The following macro KARABO_PYTHON_IMAGE_ELEMENT is used for python binding of - * @code - * karabo::util::ImageElement - * @endcode - * - * In Python: IMAGE_ELEMENT - * - */ - -#define KARABO_PYTHON_IMAGE_ELEMENT(U) \ - .def("description", (U & (U::*)(string const&))(&U::description), bp::arg("desc"), \ - bp::return_internal_reference<>()) \ - .def("displayedName", (U & (U::*)(string const&))(&U::displayedName), bp::arg("displayedName"), \ - bp::return_internal_reference<>()) \ - .def("key", (U & (U::*)(string const&))(&U::key), bp::arg("name"), bp::return_internal_reference<>()) \ - .def("alias", (U & (U::*)(int const&))(&U::alias), bp::return_internal_reference<>()) \ - .def("observerAccess", &U::observerAccess, bp::return_internal_reference<>()) \ - .def("userAccess", &U::userAccess, bp::return_internal_reference<>()) \ - .def("operatorAccess", &U::operatorAccess, bp::return_internal_reference<>()) \ - .def("expertAccess", &U::expertAccess, bp::return_internal_reference<>()) \ - .def("adminAccess", &U::adminAccess, bp::return_internal_reference<>()) \ - .def("commit", (void(U::*)())(&U::commit)) - -#endif /* KARATHON_MACROSFORPYTHON_HH */ diff --git a/src/karathon/PythonOutputHandler.cc b/src/karathon/PythonOutputHandler.cc deleted file mode 100644 index 2935f10ac9..0000000000 --- a/src/karathon/PythonOutputHandler.cc +++ /dev/null @@ -1,23 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include "PythonOutputHandler.hh" - -KARABO_REGISTER_IN_FACTORY(karabo::io::OutputHandler, karathon::PythonOutputHandler); - -KARABO_REGISTER_IN_FACTORY_1(karabo::io::OutputHandler, karathon::PythonOutputHandler, - karabo::io::AbstractOutput::Pointer); diff --git a/src/karathon/PythonOutputHandler.hh b/src/karathon/PythonOutputHandler.hh deleted file mode 100644 index 9628251c96..0000000000 --- a/src/karathon/PythonOutputHandler.hh +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: PythonOutputHandler.hh - * Author: esenov - * - * Created on September 17, 2013, 7:59 PM - */ - -#ifndef KARATHON_PYTHONOUTPUTHANDLER_HH -#define KARATHON_PYTHONOUTPUTHANDLER_HH - -#include -#include -#include -#include -#include - -#include "ScopedGILAcquire.hh" -#include "Wrapper.hh" - -namespace bp = boost::python; - -namespace karathon { - - class PythonOutputHandler : public karabo::io::OutputHandler { - public: - KARABO_CLASSINFO(PythonOutputHandler, "PythonOutputHandler", "1.0") - - PythonOutputHandler() {} - - PythonOutputHandler(const karabo::io::AbstractOutput::Pointer& output) : m_output(output) {} - - virtual ~PythonOutputHandler() {} - - void registerIOEventHandler(const boost::any& ioEventHandler) { - m_ioEventHandler = boost::any_cast(ioEventHandler); - } - - void triggerIOEvent() { - ScopedGILAcquire gil; - if (m_ioEventHandler != bp::object()) { - if (karabo::io::AbstractOutput::Pointer out = m_output.lock()) m_ioEventHandler(out); - } - } - - private: - boost::weak_ptr m_output; - bp::object m_ioEventHandler; - }; -} // namespace karathon - -#endif /* KARATHON_PYTHONOUTPUTHANDLER_HH */ diff --git a/src/karathon/ScopedGILAcquire.hh b/src/karathon/ScopedGILAcquire.hh deleted file mode 100644 index 3774b06d85..0000000000 --- a/src/karathon/ScopedGILAcquire.hh +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ScopedGILAcquire.hh - * Author: esenov - * - * Created on February 25, 2013, 2:54 PM - */ - -#ifndef SCOPEDGILACQUIRE_HH -#define SCOPEDGILACQUIRE_HH - -#include - -namespace karathon { - - class ScopedGILAcquire { - public: - inline ScopedGILAcquire() : m_gstate(PyGILState_Ensure()) {} - - inline ~ScopedGILAcquire() { - PyGILState_Release(m_gstate); - } - - private: - PyGILState_STATE m_gstate; - }; - -} // namespace karathon - - -#endif /* SCOPEDGILACQUIRE_HH */ diff --git a/src/karathon/ScopedGILRelease.hh b/src/karathon/ScopedGILRelease.hh deleted file mode 100644 index 14b5327990..0000000000 --- a/src/karathon/ScopedGILRelease.hh +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ScopedGilRelease.hh - * Author: esenov - * - * Created on February 5, 2013, 2:05 PM - */ - -#ifndef SCOPEDGILRELEASE_HH -#define SCOPEDGILRELEASE_HH - -#include - -namespace karathon { - - class ScopedGILRelease { - public: - inline ScopedGILRelease() { - if (PyGILState_Check()) m_threadState = PyEval_SaveThread(); - else m_threadState = 0; - } - - inline ~ScopedGILRelease() { - if (m_threadState) PyEval_RestoreThread(m_threadState); - } - - private: - PyThreadState* m_threadState; - }; -} // namespace karathon - -#endif /* SCOPEDGILRELEASE_HH */ diff --git a/src/karathon/SignalSlotableWrap.cc b/src/karathon/SignalSlotableWrap.cc deleted file mode 100644 index d9a0abfcc5..0000000000 --- a/src/karathon/SignalSlotableWrap.cc +++ /dev/null @@ -1,366 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include "SignalSlotableWrap.hh" - -#include - -namespace bp = boost::python; -using namespace karabo::xms; -using namespace karabo::util; -using namespace karabo::net; - -namespace karathon { - /** - * Specialisation of HandlerWrap for error handling - */ - class ErrorHandlerWrap : public HandlerWrap<> { - public: - ErrorHandlerWrap(const bp::object& handler, char const* const where) : HandlerWrap<>(handler, where) {} - - void operator()() const { - std::string msg; - std::string details; - try { - throw; // rethrow the exception - } catch (const karabo::util::RemoteException& e) { - details = e.type(); // contains e.g. id of remote side - details += ":\n"; - details += e.details(); - msg = e.type(); - msg += ": "; - msg += e.userFriendlyMsg(true); - } catch (const karabo::util::Exception& e) { - // No need to treat TimeoutException separately - msg = e.userFriendlyMsg(false); - details = e.detailedMsg(); - } catch (const std::exception& e) { - msg = e.what(); - } - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(msg, details); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - }; - - - SignalSlotableWrap::RequestorWrap::RequestorWrap(karabo::xms::SignalSlotable* signalSlotable) - : karabo::xms::SignalSlotable::Requestor(signalSlotable) {} - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy(const bp::object& replyCallback, - const bp::object& errorCallback, const bp::object& timeoutMs, - const bp::object& numCallbackArgs) { - // Forward timeout if specified - if (timeoutMs.ptr() != Py_None) { - timeout(bp::extract(timeoutMs)); - } - // Wrap error handler - AsyncErrorHandler errorHandler; - if (errorCallback.ptr() != Py_None) { - errorHandler = ErrorHandlerWrap(errorCallback, "receiveAsyncPyError"); - } - // Figure out number of arguments of callback - size_t numReturnArgs = 0ul; - if (numCallbackArgs.ptr() != Py_None) { // Passed explicitely - numReturnArgs = bp::extract(numCallbackArgs); - } else { // Deduce from callback itself - numReturnArgs = Wrapper::numArgs(replyCallback); - } - switch (numReturnArgs) { - case 0: { - // Do everthing (incl. copying) on boost::object with GIL. - boost::function handler(HandlerWrap<>(replyCallback, "receiveAsyncPy0")); - // Release GIL since receiveAsync(..) in fact synchronously writes the message. - ScopedGILRelease nogil; - // There is no move semantics for receiveAsync (yet?), but 'handler' holds the - // Python object for the replyCallback as a shared_ptr. So when 'handler' gets copied, - // the Python object itself is not ==> fine to run this without GIL. - receiveAsync(std::move(handler), std::move(errorHandler)); - break; - } - case 1: { - boost::function handler(HandlerWrapAny1(replyCallback, "receiveAsyncPy1")); - ScopedGILRelease nogil; - receiveAsync(std::move(handler), std::move(errorHandler)); - break; - } - case 2: { - boost::function handler( - HandlerWrapAny2(replyCallback, "receiveAsyncPy2")); - ScopedGILRelease nogil; - receiveAsync(std::move(handler), std::move(errorHandler)); - break; - } - case 3: { - boost::function handler( - HandlerWrapAny3(replyCallback, "receiveAsyncPy3")); - ScopedGILRelease nogil; - receiveAsync(std::move(handler), std::move(errorHandler)); - break; - } - case 4: { - boost::function - handler(HandlerWrapAny4(replyCallback, "receiveAsyncPy4")); - ScopedGILRelease nogil; - receiveAsync(std::move(handler), - std::move(errorHandler)); - break; - } - default: - throw KARABO_SIGNALSLOT_EXCEPTION("Detected/specified " + toString(numReturnArgs) += - " (> 4) arguments"); - } - } - - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy0(const bp::object& replyCallback) { - // replyCallback, errorCallback, timeoutMs, numCallbackArgs - receiveAsyncPy(replyCallback, bp::object(), bp::object(), bp::object(0)); - } - - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy1(const bp::object& replyCallback) { - // replyCallback, errorCallback, timeoutMs, numCallbackArgs - receiveAsyncPy(replyCallback, bp::object(), bp::object(), bp::object(1)); - } - - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy2(const bp::object& replyCallback) { - // replyCallback, errorCallback, timeoutMs, numCallbackArgs - receiveAsyncPy(replyCallback, bp::object(), bp::object(), bp::object(2)); - } - - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy3(const bp::object& replyCallback) { - // replyCallback, errorCallback, timeoutMs, numCallbackArgs - receiveAsyncPy(replyCallback, bp::object(), bp::object(), bp::object(3)); - } - - - void SignalSlotableWrap::RequestorWrap::receiveAsyncPy4(const bp::object& replyCallback) { - // replyCallback, errorCallback, timeoutMs, numCallbackArgs - receiveAsyncPy(replyCallback, bp::object(), bp::object(), bp::object(4)); - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::waitForReply(const int& milliseconds) { - try { - timeout(milliseconds); - karabo::util::Hash::Pointer body, header; - - { - ScopedGILRelease nogil; - receiveResponse(header, body); - // The header key "error" indicates whether an exception was thrown during the remote call - if (header->has("error") && header->get("error")) { - // Handling an error, so double check that input is as expected, i.e. body has key "a1": - const boost::optional textNode = body->find("a1"); - const std::string text(textNode && textNode->is() - ? textNode->getValue() - : "Error signaled, but body without string at key \"a1\""); - const boost::optional detailsNode = body->find("a2"); - const std::string& details = (detailsNode && detailsNode->is() // since Karabo 2.14.0 - ? detailsNode->getValue() - : std::string()); - throw karabo::util::RemoteException(text, header->get("signalInstanceId"), details); - } - } - - size_t arity = body->size(); - - switch (arity) { - case 0: - return prepareTuple0(*body); - case 1: - return prepareTuple1(*body); - case 2: - return prepareTuple2(*body); - case 3: - return prepareTuple3(*body); - case 4: - return prepareTuple4(*body); - default: - throw KARABO_SIGNALSLOT_EXCEPTION( - "Too many arguments send as response (max 4 are currently supported"); - } - } catch (const karabo::util::RemoteException&) { - // Just rethrow as is: No further addition to Karabo stack trace, but keeping type and details(). - throw; - } catch (const karabo::util::TimeoutException&) { - throw; // Rethrow as TimeoutException for proper conversion to Python TimeoutError - } catch (const karabo::util::Exception& e) { - // No need to add stack trace from detailesMsg() here - code converting this to Python exception will do so - KARABO_RETHROW_AS(KARABO_SIGNALSLOT_EXCEPTION("Error while receiving message on instance \"" + - m_signalSlotable->getInstanceId() + "\"")); - // For compiler happiness - return bp::make_tuple(); - } - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::prepareTuple0(const karabo::util::Hash& body) { - return bp::make_tuple(); - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::prepareTuple1(const karabo::util::Hash& body) { - bp::object a1 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a1")); - return bp::make_tuple(a1); - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::prepareTuple2(const karabo::util::Hash& body) { - bp::object a1 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a1")); - bp::object a2 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a2")); - return bp::make_tuple(a1, a2); - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::prepareTuple3(const karabo::util::Hash& body) { - bp::object a1 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a1")); - bp::object a2 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a2")); - bp::object a3 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a3")); - return bp::make_tuple(a1, a2, a3); - } - - - bp::tuple SignalSlotableWrap::RequestorWrap::prepareTuple4(const karabo::util::Hash& body) { - bp::object a1 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a1")); - bp::object a2 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a2")); - bp::object a3 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a3")); - bp::object a4 = Wrapper::deepCopyHashLike(HashWrap::get(body, "a4")); - return bp::make_tuple(a1, a2, a3, a4); - } - - - SignalSlotableWrap::AsyncReplyWrap::AsyncReplyWrap(SignalSlotable* signalSlotable) - : karabo::xms::SignalSlotable::AsyncReply(signalSlotable) {} - - - void SignalSlotableWrap::AsyncReplyWrap::replyPy0() const { - ScopedGILRelease nogil; - // Call inherited operator(..) - no GIL since that synchronously sends a message: - (*this)(); - } - - - void SignalSlotableWrap::AsyncReplyWrap::replyPy1(const bp::object& a1) const { - // Convert Python object to boost::any - may involve a copy :-( - boost::any a1Any; - Wrapper::toAny(a1, a1Any); - // Call inherited operator(..) - no GIL since that synchronously sends a message: - ScopedGILRelease nogil; - (*this)(a1Any); - } - - - void SignalSlotableWrap::AsyncReplyWrap::replyPy2(const bp::object& a1, const bp::object& a2) const { - // Convert Python objects to boost::any - may involve copies :-( - boost::any a1Any, a2Any; - Wrapper::toAny(a1, a1Any); - Wrapper::toAny(a2, a2Any); - // Call inherited operator(..) - no GIL since that synchronously sends a message: - ScopedGILRelease nogil; - (*this)(a1Any, a2Any); - } - - - void SignalSlotableWrap::AsyncReplyWrap::replyPy3(const bp::object& a1, const bp::object& a2, - const bp::object& a3) const { - // Convert Python objects to boost::any - may involve copies :-( - boost::any a1Any, a2Any, a3Any; - Wrapper::toAny(a1, a1Any); - Wrapper::toAny(a2, a2Any); - Wrapper::toAny(a3, a3Any); - // Call inherited operator(..) - no GIL since that synchronously sends a message: - ScopedGILRelease nogil; - (*this)(a1Any, a2Any, a3Any); - } - - - void SignalSlotableWrap::AsyncReplyWrap::replyPy4(const bp::object& a1, const bp::object& a2, const bp::object& a3, - const bp::object& a4) const { - // Convert Python objects to boost::any - may involve copies :-( - boost::any a1Any, a2Any, a3Any, a4Any; - Wrapper::toAny(a1, a1Any); - Wrapper::toAny(a2, a2Any); - Wrapper::toAny(a3, a3Any); - Wrapper::toAny(a4, a4Any); - // Call inherited operator(..) - no GIL since that synchronously sends a message: - ScopedGILRelease nogil; - (*this)(a1Any, a2Any, a3Any, a4Any); - } - - - SignalSlotableWrap::SignalSlotableWrap(const std::string& instanceId, - const karabo::util::Hash& connectionParameters, int heartbeatInterval, - const karabo::util::Hash& instanceInfo) - : SignalSlotable(instanceId, connectionParameters, heartbeatInterval, instanceInfo) {} - - - SignalSlotableWrap::~SignalSlotableWrap() {} - - - void SignalSlotableWrap::registerSlotPy(const bp::object& slotFunction, std::string slotName, int numArgs) { - if (slotName.empty()) { - slotName = bp::extract((slotFunction.attr("__name__"))); - } - boost::mutex::scoped_lock lock(m_signalSlotInstancesMutex); - SlotInstances::const_iterator it = m_slotInstances.find(slotName); - if (it != m_slotInstances.end()) { // Already registered - (boost::static_pointer_cast(it->second))->registerSlotFunction(slotFunction, numArgs); - } else { - boost::shared_ptr s(boost::make_shared(slotName)); - s->registerSlotFunction(slotFunction, numArgs); // Bind user's slot-function to Slot - m_slotInstances[slotName] = s; - } - } - - - karabo::xms::InputChannel::Pointer SignalSlotableWrap::createInputChannelPy(const std::string& channelName, - const karabo::util::Hash& config, - const bp::object& onDataHandler, - const bp::object& onInputHandler, - const bp::object& onEndOfStreamHandler, - const bp::object& connectionTracker) { - // Basically just call createInputChannel from C++, but take care that data and input handlers - // stay empty if their input is empty, although the proxies are able - // to deal with 'None' Python handlers (as we make use of for the end of stream handler). - DataHandler dataHandler = DataHandler(); - InputHandler inputHandler = InputHandler(); - if (onDataHandler != bp::object()) { - // or: if (onDataHandler.ptr() != Py_None) { - dataHandler = InputChannelWrap::DataHandlerWrap(onDataHandler, "data"); - } - if (onInputHandler != bp::object()) { - inputHandler = HandlerWrap(onInputHandler, "input"); - } - - return this->createInputChannel( - channelName, config, dataHandler, inputHandler, - HandlerWrap(onEndOfStreamHandler, "EOS"), - HandlerWrap(connectionTracker, - "channelStatusTracker")); - } -} // namespace karathon diff --git a/src/karathon/SignalSlotableWrap.hh b/src/karathon/SignalSlotableWrap.hh deleted file mode 100644 index 5479eaa9cc..0000000000 --- a/src/karathon/SignalSlotableWrap.hh +++ /dev/null @@ -1,322 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: SignalSlotableWrap.hh - * Author: - * Contributions: - * - * Created on March 19, 2012, 11:22 AM - */ - -#ifndef KARATHON_SIGNALSLOTABLE_HH -#define KARATHON_SIGNALSLOTABLE_HH - -#include -#include -#include -#include -#include -#include - -#include "PyXmsInputOutputChannel.hh" -#include "ScopedGILRelease.hh" -#include "SignalWrap.hh" -#include "SlotWrap.hh" -#include "Wrapper.hh" - -namespace bp = boost::python; - -namespace karathon { - - class SignalSlotableWrap : public karabo::xms::SignalSlotable { - public: - KARABO_CLASSINFO(SignalSlotableWrap, "SignalSlotableWrap", "1.0") - - class RequestorWrap : public karabo::xms::SignalSlotable::Requestor { - public: - explicit RequestorWrap(karabo::xms::SignalSlotable* signalSlotable); - - RequestorWrap timeoutPy(const int& milliseconds); - - template - RequestorWrap& requestPy(const std::string& slotInstanceId, const std::string& slotFunction, - const Args&... args) { - try { - auto body = boost::make_shared(); - packPy(*body, args...); - ScopedGILRelease nogil; - registerRequest(slotInstanceId, prepareRequestHeader(slotInstanceId, slotFunction), body); - } catch (...) { - KARABO_RETHROW - } - return *this; - } - - template - RequestorWrap& requestNoWaitPy(const std::string& requestSlotInstanceId, - const std::string& requestSlotFunction, - const std::string replySlotInstanceId, const std::string& replySlotFunction, - const Args&... args) { - try { - auto body = boost::make_shared(); - packPy(*body, args...); - ScopedGILRelease nogil; - karabo::util::Hash::Pointer header = prepareRequestNoWaitHeader( - requestSlotInstanceId, requestSlotFunction, replySlotInstanceId, replySlotFunction); - registerRequest(requestSlotInstanceId, header, body); - sendRequest(); - } catch (...) { - KARABO_RETHROW - } - return *this; - } - - void receiveAsyncPy(const bp::object& replyCallback, const bp::object& errorCallback = bp::object(), - const bp::object& timeoutMs = bp::object(), - const bp::object& numCallbackArgs = bp::object()); - - void receiveAsyncPy0(const bp::object& replyCallback); - - void receiveAsyncPy1(const bp::object& replyCallback); - - void receiveAsyncPy2(const bp::object& replyCallback); - - void receiveAsyncPy3(const bp::object& replyCallback); - - void receiveAsyncPy4(const bp::object& replyCallback); - - bp::tuple waitForReply(const int& milliseconds); - - private: - bp::tuple prepareTuple0(const karabo::util::Hash& body); - - bp::tuple prepareTuple1(const karabo::util::Hash& body); - - bp::tuple prepareTuple2(const karabo::util::Hash& body); - - bp::tuple prepareTuple3(const karabo::util::Hash& body); - - bp::tuple prepareTuple4(const karabo::util::Hash& body); - }; - - class AsyncReplyWrap : public karabo::xms::SignalSlotable::AsyncReply { - public: - explicit AsyncReplyWrap(SignalSlotable* signalSlotable); - - void replyPy0() const; - - void replyPy1(const bp::object& a1) const; - - void replyPy2(const bp::object& a1, const bp::object& a2) const; - - void replyPy3(const bp::object& a1, const bp::object& a2, const bp::object& a3) const; - - void replyPy4(const bp::object& a1, const bp::object& a2, const bp::object& a3, const bp::object& a4) const; - }; - - AsyncReplyWrap createAsyncReply() { - return SignalSlotableWrap::AsyncReplyWrap(this); - } - - public: - SignalSlotableWrap(const std::string& instanceId = generateInstanceId(), - const karabo::util::Hash& connectionParameters = karabo::util::Hash(), - int heartbeatInterval = 10, const karabo::util::Hash& instanceInfo = karabo::util::Hash()); - - virtual ~SignalSlotableWrap(); - - static boost::shared_ptr create( - const std::string& instanceId = generateInstanceId(), - const karabo::util::Hash& connectionParameters = karabo::util::Hash(), int heartbeatInterval = 10, - const karabo::util::Hash& instanceInfo = karabo::util::Hash()) { - return boost::shared_ptr( - new SignalSlotableWrap(instanceId, connectionParameters, heartbeatInterval, instanceInfo)); - } - - void start() { - ScopedGILRelease nogil; - try { - karabo::xms::SignalSlotable::start(); - } catch (const std::exception& e) { - // Make sure that we get something in the log file and not only in standard output/error - KARABO_LOG_FRAMEWORK_ERROR << e.what(); - KARABO_RETHROW; - } - } - - bp::object getInstanceId() { - return bp::object(SignalSlotable::getInstanceId()); - } - - bp::tuple existsPy(const std::string& instanceId) { - std::pair result; - { - ScopedGILRelease nogil; - result = exists(instanceId); - } - return bp::make_tuple(result.first, bp::object(result.second)); - } - - karabo::util::Hash getAvailableInstancesPy(bool activateTracking) { - return this->getAvailableInstances(activateTracking); - } - - bp::object getAvailableSignalsPy(const std::string& instanceId) { - return Wrapper::fromStdVectorToPyList(this->getAvailableSignals(instanceId)); - } - - bp::object getAvailableSlotsPy(const std::string& instanceId) { - return Wrapper::fromStdVectorToPyList(this->getAvailableSlots(instanceId)); - } - - void registerSlotPy(const bp::object& slotFunction, std::string slotName, int numArg); - - template - void registerSignalPy(const std::string& funcName, const Args&... args) { - // Arguments are ignored, but required to partially deduce the signature of the signal in Python: - // All args will always be bp::object, but at least the number of arguments defines the signal signature - registerSignal(funcName); - } - - template - void registerSystemSignalPy(const std::string& funcName, const Args&... args) { - // Arguments are ignored, but required to partially deduce the signature of the signal in Python: - // All args will always be bp::object, but at least the number of arguments defines the signal signature - registerSystemSignal(funcName); - } - - template - SignalSlotableWrap::RequestorWrap requestPy(std::string instanceId, const std::string& functionName, - const Args&... args) { - if (instanceId.empty()) instanceId = m_instanceId; - return SignalSlotableWrap::RequestorWrap(this).requestPy(instanceId, functionName, args...); - } - - template - SignalSlotableWrap::RequestorWrap requestNoWaitPy(std::string requestSlotInstanceId, - const std::string& requestSlotFunction, - std::string replySlotInstanceId, - const std::string& replySlotFunction, const Args&... args) { - if (requestSlotInstanceId.empty()) requestSlotInstanceId = m_instanceId; - if (replySlotInstanceId.empty()) replySlotInstanceId = m_instanceId; - return SignalSlotableWrap::RequestorWrap(this).requestNoWaitPy( - requestSlotInstanceId, requestSlotFunction, replySlotInstanceId, replySlotFunction, args...); - } - - template - void emitPy(const std::string& signalFunction, const Args&... args) { - auto s = getSignal(signalFunction); - if (s) { - auto hash = boost::make_shared(); - packPy(*hash, args...); - s->emit(hash); - } - } - - template - void callPy(const std::string& instanceId, const std::string& functionName, const Args&... args) const { - auto body = boost::make_shared(); - packPy(*body, args...); - const std::string& id = (instanceId.empty() ? m_instanceId : instanceId); - auto header = prepareCallHeader(id, functionName); - doSendMessage(id, header, body, KARABO_SYS_PRIO, KARABO_SYS_TTL); - } - - template - void replyPy(const Args&... args) { - auto reply(boost::make_shared()); - packPy(*reply, args...); - registerReply(reply); - } - - bool connectPy(const std::string& signalInstanceId, const std::string& signalFunction, - const std::string& slotInstanceId, const std::string& slotFunction) { - ScopedGILRelease nogil; - return this->connect(signalInstanceId, signalFunction, slotInstanceId, slotFunction); - } - - bool connectPy_old(const std::string& signalFunction, const std::string& slotFunction) { - ScopedGILRelease nogil; - return this->connect(signalFunction, slotFunction); - } - - void registerSlotCallGuardHandlerPy(const bp::object& handler) { - registerSlotCallGuardHandler( - HandlerWrap(handler, "slot call guard")); - } - - void registerPerformanceStatisticsHandlerPy(const bp::object& handler) { - registerPerformanceStatisticsHandler( - HandlerWrap(handler, "performance measurement")); - } - - void registerBrokerErrorHandlerPy(const bp::object& handler) { - registerBrokerErrorHandler(HandlerWrap(handler, "broker error")); - } - - karabo::xms::OutputChannel::Pointer createOutputChannelPy( - const std::string& channelName, const karabo::util::Hash& config, - const bp::object& onOutputPossibleHandler = bp::object()) { - using Wrap = HandlerWrap; - return createOutputChannel(channelName, config, Wrap(onOutputPossibleHandler, "IOEvent")); - } - - karabo::xms::InputChannel::Pointer createInputChannelPy(const std::string& channelName, - const karabo::util::Hash& config, - const bp::object& onDataHandler = bp::object(), - const bp::object& onInputHandler = bp::object(), - const bp::object& onEndOfStreamHandler = bp::object(), - const bp::object& connectionTracker = bp::object()); - - void connectInputChannelsPy() { - ScopedGILRelease nogil; - this->connectInputChannels(boost::system::error_code()); - } - - bp::object getOutputChannelPy(const std::string& name) { - return bp::object(getOutputChannel(name)); - } - - bp::object getInputChannelPy(const std::string& name) { - return bp::object(getInputChannel(name)); - } - - bp::list getInputChannelNamesPy() { - bp::list result; - for (const auto& inputNameChannel : getInputChannels()) { - result.append(inputNameChannel.first); - } - return result; - } - - void registerDataHandlerPy(const std::string& channelName, const bp::object& handler) { - registerDataHandler(channelName, InputChannelWrap::DataHandlerWrap(handler, "data")); - } - - void registerInputHandlerPy(const std::string& channelName, const bp::object& handler) { - registerInputHandler(channelName, HandlerWrap(handler, "input")); - } - - void registerEndOfStreamHandlerPy(const std::string& channelName, const bp::object& handler) { - registerEndOfStreamHandler(channelName, - HandlerWrap(handler, "EOS")); - } - }; -} // namespace karathon - -#endif /* KARATHON_SIGNALSLOTABLE_HH */ diff --git a/src/karathon/SignalWrap.hh b/src/karathon/SignalWrap.hh deleted file mode 100644 index 035684852d..0000000000 --- a/src/karathon/SignalWrap.hh +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: SignalWrap.hh - * Author: irinak - * - * Created on March 19, 2012, 11:37 AM - */ - -#ifndef KARATHON_SIGNALWRAP_HH -#define KARATHON_SIGNALWRAP_HH - -#include -#include -#include - -#include "HashWrap.hh" -#include "ScopedGILRelease.hh" - -namespace bp = boost::python; - -namespace karabo { - - namespace xms { - // Forward SignalSlotable - class SignalSlotable; - } // namespace xms -} // namespace karabo - -namespace karathon { - - class SignalWrap : public karabo::xms::Signal { - public: - SignalWrap(const karabo::xms::SignalSlotable* signalSlotable, const karabo::net::Broker::Pointer& producer, - const std::string& instanceId, const std::string& signalId, const int priority = KARABO_SYS_PRIO, - const int messageTimeToLive = KARABO_SYS_TTL) - : karabo::xms::Signal(signalSlotable, producer, instanceId, signalId, priority, messageTimeToLive) {} - - template - void emitPy(const Args&... args) { - auto body = boost::make_shared(); - packPy(*body, args...); - ScopedGILRelease nogil; - emit(body); - } - }; -} // namespace karathon - -#endif /* KARATHON_SIGNALWRAP_HH */ diff --git a/src/karathon/SlotWrap.cc b/src/karathon/SlotWrap.cc deleted file mode 100644 index c506936de5..0000000000 --- a/src/karathon/SlotWrap.cc +++ /dev/null @@ -1,153 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -#include "SlotWrap.hh" - -#include - -#include "ScopedGILAcquire.hh" -#include "Wrapper.hh" // for getPythonExceptionStrings() - -namespace bp = boost::python; - -namespace karathon { - - - SlotWrap::SlotWrap(const std::string& slotFunction) : karabo::xms::Slot(slotFunction) {} - - - SlotWrap::~SlotWrap() { - ScopedGILAcquire gil; // for bp::object destructor - m_slotFunction.reset(); - } - - - void SlotWrap::registerSlotFunction(const bp::object& slotHandler, int numArgs) { - // We accept ONLY the python callable - if (!PyCallable_Check(slotHandler.ptr())) { - throw KARABO_PARAMETER_EXCEPTION("The argument is not callable."); - } - - // Note: In C++ there is a list of slot handlers to which is appended - here we overwrite any previous handler. - // Note 2: Create pointer to be able to ensure that deletion can be done with GIL acquired. - std::unique_ptr newHandler(std::make_unique(slotHandler)); - m_slotFunction.swap(newHandler); - if (numArgs >= 0) { - m_arity = numArgs; - } else { - // Undefined number of arguments, try to figure out - m_arity = Wrapper::numArgs(*m_slotFunction); - } - } - - - void SlotWrap::doCallRegisteredSlotFunctions(const karabo::util::Hash& body) { - ScopedGILAcquire gil; - - switch (m_arity) { - case 4: - callFunction4(body); - break; - case 3: - callFunction3(body); - break; - case 2: - callFunction2(body); - break; - case 1: - callFunction1(body); - break; - case 0: - callFunction0(body); - break; - default: - throw KARABO_SIGNALSLOT_EXCEPTION( - "Too many arguments send to python slot (max 4 are currently supported"); - } - } - - - void SlotWrap::callFunction0(const karabo::util::Hash& body) { - try { - (*m_slotFunction)(); - } catch (const bp::error_already_set&) { - rethrowPythonException(); - } - } - - - bp::object SlotWrap::getBodyArgument(const karabo::util::Hash& body, const char* key) const { - // Avoid using HashWrap::get: it returns None if key missing (but we want the exception!). - // Since get uses internally this getRef with the same const_cast, that is safe here as well - return HashWrap::getRef(const_cast(body), bp::object(key)); - } - - - void SlotWrap::callFunction1(const karabo::util::Hash& body) { - bp::object a1 = getBodyArgument(body, "a1"); - try { - (*m_slotFunction)(a1); - } catch (const bp::error_already_set&) { - rethrowPythonException(); - } - } - - - void SlotWrap::callFunction2(const karabo::util::Hash& body) { - bp::object a1 = getBodyArgument(body, "a1"); - bp::object a2 = getBodyArgument(body, "a2"); - try { - (*m_slotFunction)(a1, a2); - } catch (const bp::error_already_set&) { - rethrowPythonException(); - } - } - - - void SlotWrap::callFunction3(const karabo::util::Hash& body) { - bp::object a1 = getBodyArgument(body, "a1"); - bp::object a2 = getBodyArgument(body, "a2"); - bp::object a3 = getBodyArgument(body, "a3"); - try { - (*m_slotFunction)(a1, a2, a3); - } catch (const bp::error_already_set&) { - rethrowPythonException(); - } - } - - - void SlotWrap::callFunction4(const karabo::util::Hash& body) { - bp::object a1 = getBodyArgument(body, "a1"); - bp::object a2 = getBodyArgument(body, "a2"); - bp::object a3 = getBodyArgument(body, "a3"); - bp::object a4 = getBodyArgument(body, "a4"); - try { - (*m_slotFunction)(a1, a2, a3, a4); - } catch (const bp::error_already_set&) { - rethrowPythonException(); - } - } - - - void SlotWrap::rethrowPythonException() { - std::string pythonErrorMessage, pythonErrorDetails; - std::tie(pythonErrorMessage, pythonErrorDetails) = getPythonExceptionStrings(); - - throw KARABO_PYTHON_EXCEPTION2(pythonErrorMessage, pythonErrorDetails); - } - -} // namespace karathon diff --git a/src/karathon/SlotWrap.hh b/src/karathon/SlotWrap.hh deleted file mode 100644 index 6f4d120ec6..0000000000 --- a/src/karathon/SlotWrap.hh +++ /dev/null @@ -1,71 +0,0 @@ -/* - * $Id$ - * - * Author: - * - * Created on February 6, 2011, 2:25 PM - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#ifndef KARATHON_SLOTWRAP_HH -#define KARATHON_SLOTWRAP_HH - -#include -#include - -#include "HashWrap.hh" -#include "karabo/xms/Slot.hh" - -namespace bp = boost::python; - -namespace karathon { - - class SlotWrap : public karabo::xms::Slot { - // unique_ptr seems more light weight than shared_ptr (no thread guarantees) - std::unique_ptr m_slotFunction; - size_t m_arity; // arity of position arguments, except *args - - public: - SlotWrap(const std::string& slotFunction); - - virtual ~SlotWrap(); - - void registerSlotFunction(const bp::object& slotHandler, int numArgs); - - private: // function - void doCallRegisteredSlotFunctions(const karabo::util::Hash& body); - - void callFunction0(const karabo::util::Hash& body); - - void callFunction1(const karabo::util::Hash& body); - - void callFunction2(const karabo::util::Hash& body); - - void callFunction3(const karabo::util::Hash& body); - - void callFunction4(const karabo::util::Hash& body); - - /// Helper for callFunction to get argument with given key ("a1", ..., or "a4") out of body. - /// Throws if that key is missing. - bp::object getBodyArgument(const karabo::util::Hash& body, const char* key) const; - - void rethrowPythonException(); - }; -} // namespace karathon - -#endif diff --git a/src/karathon/ToNumpy.hh b/src/karathon/ToNumpy.hh deleted file mode 100644 index a0a216a199..0000000000 --- a/src/karathon/ToNumpy.hh +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: ToNumpy.hh - * Author: - * - * Created on May 26, 2014, 11:11 AM - */ - -#ifndef KARATHON_TONUMPY_HH -#define KARATHON_TONUMPY_HH - -#include - -#include - -namespace karathon { - - class ToNumpy { - public: - typedef int ReturnType; - - template - static ReturnType to() { - throw KARABO_NOT_IMPLEMENTED_EXCEPTION("Conversion to required type not implemented"); - } - }; - - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, BOOL, NPY_BOOL) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, CHAR, NPY_BYTE) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, INT8, NPY_BYTE) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, UINT8, NPY_UBYTE) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, INT16, NPY_SHORT) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, UINT16, NPY_USHORT) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, INT32, NPY_INT) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, UINT32, NPY_UINT) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, INT64, NPY_LONGLONG) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, UINT64, NPY_ULONGLONG) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, FLOAT, NPY_FLOAT) - KARABO_MAP_TO_REFERENCE_TYPE(ToNumpy, DOUBLE, NPY_DOUBLE) - -} // namespace karathon -#endif diff --git a/src/karathon/Wrapper.cc b/src/karathon/Wrapper.cc deleted file mode 100644 index 36385a3158..0000000000 --- a/src/karathon/Wrapper.cc +++ /dev/null @@ -1,908 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: Wrapper.cc - * Author: esenov - * - * Created on March 17, 2013, 11:06 PM - */ - -#include "Wrapper.hh" - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace karathon { - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_BOOL); - PyArrayObject* arr = reinterpret_cast(pyobj); - bool* data = reinterpret_cast(PyArray_DATA(arr)); - for (int i = 0; i < PyArray_SIZE(arr); i++) { - data[i] = v[i]; - } - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_SHORT); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_USHORT); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_INT); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_UINT); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_LONGLONG); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_ULONGLONG); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_FLOAT); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); // - } - return Wrapper::fromStdVectorToPyList(v); - } - - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag) { - if (numpyFlag) { - int nd = 1; - npy_intp dims[1]; - dims[0] = v.size(); - PyObject* pyobj = PyArray_SimpleNew(nd, dims, NPY_DOUBLE); // reinterpret_cast (&v[0])); - PyArrayObject* arr = reinterpret_cast(pyobj); - memcpy(PyArray_DATA(arr), &v[0], PyArray_NBYTES(arr)); - return bp::object(bp::handle<>(pyobj)); - } - return Wrapper::fromStdVectorToPyList(v); - } - - bp::object Wrapper::toObject(const boost::any& operand, bool numpyFlag) { - try { - if (operand.type() == typeid(bool)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(char)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(signed char)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(unsigned char)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(short)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(unsigned short)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(int)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(unsigned int)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(long long)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(unsigned long long)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(float)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(double)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(std::complex)) { - return bp::object(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::complex)) { - return bp::object(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::string)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(boost::filesystem::path)) { - return bp::object(boost::any_cast(operand).string()); - } else if (operand.type() == typeid(karabo::util::CppNone)) { - return bp::object(); - } else if (operand.type() == typeid(karabo::util::Hash)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(karabo::util::Hash::Pointer)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyByteArray(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyByteArray(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyByteArray(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyArray(boost::any_cast >(operand), numpyFlag); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyList(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::vector)) { - return fromStdVectorToPyListNone(boost::any_cast >(operand)); - } else if (operand.type() == typeid(karabo::util::Schema)) { - return bp::object(boost::any_cast(operand)); - } else if (operand.type() == typeid(std::vector)) { - return bp::object(boost::any_cast >(operand)); - } else if (operand.type() == typeid(std::vector)) { - return bp::object(boost::any_cast >(operand)); - } else if (operand.type() == typeid(bp::object) && - hasattr(boost::any_cast(operand), "__name__")) { - return boost::any_cast(operand); - } - throw KARABO_PYTHON_EXCEPTION("Failed to convert inner Hash type of python object"); - } catch (const boost::bad_any_cast& e) { - KARABO_RETHROW_AS(KARABO_CAST_EXCEPTION(e.what())); - } - return bp::object(); // make compiler happy -- we never reach this statement - } - - bp::object Wrapper::toCustomObject(karabo::util::Hash::Node& node) { - karabo::util::Hash::Pointer hash = - karabo::util::Hash::Pointer(&node.getValue(), null_deleter()); - if (node.hasAttribute(KARABO_HASH_CLASS_ID)) { // Hash actually holds data for a custom class - const std::string& classId = node.getAttribute(KARABO_HASH_CLASS_ID); - if (classId == "NDArray") { - return fromNDArrayToPyArray(reinterpret_cast(*hash)); - } - if (classId == "ImageData") { - const karabo::xms::ImageData& imgData = reinterpret_cast(*hash); - return bp::object(karabo::xms::ImageData::Pointer(new karabo::xms::ImageData(imgData))); - } - } - return bp::object(hash); - } - - - // Helper for Wrapper::toAny below: - karabo::util::Types::ReferenceType bestIntegerType(const bp::object& obj) { - long long const kNegInt32Min = -(1LL << 31); - long long const kPosUint32Max = (1LL << 32) - 1; - long long const kPosInt32Max = (1LL << 31) - 1; - long long const kPosInt64Max = (1ULL << 63) - 1; - - int overflow = 0; - PY_LONG_LONG value = PyLong_AsLongLongAndOverflow(obj.ptr(), &overflow); - if (overflow == 0) { - if (value < 0) { - if (value < kNegInt32Min) { - return karabo::util::Types::INT64; - } else { - return karabo::util::Types::INT32; - } - } else { - if (value > kPosUint32Max) { - if (value <= kPosInt64Max) { - return karabo::util::Types::INT64; - } else { - return karabo::util::Types::UINT64; - } - } else { - if (value <= kPosInt32Max) { - return karabo::util::Types::INT32; - } else { - return karabo::util::Types::UINT32; - } - } - } - } else { - // So 'long long', i.e. INT64, overflows. Best try is UINT64 that needs PyLong_AsUnsignedLongLong - // for conversion. Note that that will raise a Python exception if even that overflows. - return karabo::util::Types::UINT64; - } - } - - karabo::util::Types::ReferenceType Wrapper::toAny(const bp::object& obj, boost::any& any) { - if (obj.ptr() == Py_None) { - any = karabo::util::CppNone(); - return karabo::util::Types::NONE; - } - if (PyBool_Check(obj.ptr())) { - bool b = bp::extract(obj); - any = b; - return karabo::util::Types::BOOL; - } - if (PyLong_Check(obj.ptr())) { - // An integer - let's find out which one fits: - const karabo::util::Types::ReferenceType type = bestIntegerType(obj); - if (type == karabo::util::Types::UINT64) { - // Raises a Python exception if it overflows: - any = PyLong_AsUnsignedLongLong(obj.ptr()); - } else { - const PY_LONG_LONG value = PyLong_AsLongLong(obj.ptr()); - switch (type) { - case karabo::util::Types::INT32: - any = static_cast(value); - break; - case karabo::util::Types::UINT32: - any = static_cast(value); - break; - case karabo::util::Types::INT64: - any = static_cast(value); - break; - default: - // Should never come here! - throw KARABO_PYTHON_EXCEPTION("Unsupported int type " + toString(type)); - } - } - return type; - } - if (PyFloat_Check(obj.ptr())) { - double b = bp::extract(obj); - any = b; - return karabo::util::Types::DOUBLE; - } - if (PyComplex_Check(obj.ptr())) { - std::complex b = bp::extract >(obj); - any = b; - return karabo::util::Types::COMPLEX_DOUBLE; - } - if (PyUnicode_Check(obj.ptr())) { - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(obj.ptr(), &size); - string b(data, size); - any = b; - return karabo::util::Types::STRING; - } - if (PyBytes_Check(obj.ptr())) { - size_t size = PyBytes_Size(obj.ptr()); - char* data = PyBytes_AsString(obj.ptr()); - std::vector b(data, data + size); - any = b; - return karabo::util::Types::VECTOR_CHAR; - } - if (PyByteArray_Check(obj.ptr())) { - size_t size = PyByteArray_Size(obj.ptr()); - char* data = PyByteArray_AsString(obj.ptr()); - std::vector b(data, data + size); - any = b; - return karabo::util::Types::VECTOR_CHAR; - } - if (bp::extract(obj).check()) { - char* const b = bp::extract(obj); - any = b; - return karabo::util::Types::PTR_CHAR; - } - if (bp::extract(obj).check()) { - wchar_t* const b = bp::extract(obj); - any = b; - return karabo::util::Types::PTR_CHAR; // TODO: Define WCHAR and PTR_WCHAR. Check with Burkhard and Martin - } - if (bp::extract >(obj).check()) { - std::vector const b = bp::extract >(obj); - any = b; - return karabo::util::Types::VECTOR_STRING; - } - if (bp::extract(obj).check()) { - karabo::util::Hash h = bp::extract(obj); - any = h; - return karabo::util::Types::HASH; - } - if (bp::extract(obj).check()) { - karabo::util::Hash::Pointer h = bp::extract(obj); - any = h; - return karabo::util::Types::HASH_POINTER; - } - if (bp::extract(obj).check()) { - karabo::util::Schema s = bp::extract(obj); - any = s; - return karabo::util::Types::SCHEMA; - } - if (bp::extract >(obj).check()) { - std::vector vhash = bp::extract >(obj); - any = vhash; - return karabo::util::Types::VECTOR_HASH; - } - if (bp::extract >(obj).check()) { - std::vector vhash = - bp::extract >(obj); - any = vhash; - return karabo::util::Types::VECTOR_HASH_POINTER; - } - if (PyArray_Check(obj.ptr())) { - PyArrayObject* arr = reinterpret_cast(obj.ptr()); - karabo::util::NDArray nd = fromPyArrayToNDArray(arr); - any = reinterpret_cast(nd); - return karabo::util::Types::HASH; - } - if (PyList_Check(obj.ptr())) { - bp::ssize_t size = bp::len(obj); - if (size == 0) { - any = std::vector(); - return karabo::util::Types::VECTOR_STRING; - } - bp::object list0 = obj[0]; - if (list0.ptr() == Py_None) { - std::vector v; - for (bp::ssize_t i = 0; i < size; ++i) v.push_back(karabo::util::CppNone()); - any = v; - return karabo::util::Types::VECTOR_NONE; - } - if (PyBool_Check(list0.ptr())) { - std::vector v(size); // Special case here - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = v; - return karabo::util::Types::VECTOR_BOOL; - } - if (PyLong_Check(list0.ptr())) { - // First item is an integer - assume that all items are! - karabo::util::Types::ReferenceType broadestType = karabo::util::Types::INT32; - for (bp::ssize_t i = 0; i < size; ++i) { - const karabo::util::Types::ReferenceType type = bestIntegerType(obj[i]); - // This relies on the fact that the enums ReferenceType have the order INT32, UINT32, INT64, UINT64 - if (type > broadestType) { - broadestType = type; - // Stop loop if cannot get broader... - if (broadestType == karabo::util::Types::UINT64) break; - } - } - if (broadestType == karabo::util::Types::INT32) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = std::move(v); - return karabo::util::Types::VECTOR_INT32; - } else if (broadestType == karabo::util::Types::UINT32) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = std::move(v); - return karabo::util::Types::VECTOR_UINT32; - } else if (broadestType == karabo::util::Types::INT64) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = std::move(v); - return karabo::util::Types::VECTOR_INT64; - } else if (broadestType == karabo::util::Types::UINT64) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = std::move(v); - return karabo::util::Types::VECTOR_UINT64; - } else { - // Should never come here! - throw KARABO_PYTHON_EXCEPTION("Unsupported int type " + toString(broadestType)); - } - } - if (PyFloat_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = v; - return karabo::util::Types::VECTOR_DOUBLE; - } - if (PyUnicode_Check(list0.ptr())) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - Py_ssize_t size; - const char* data = PyUnicode_AsUTF8AndSize(static_cast(obj[i]).ptr(), &size); - v[i] = string(data, size); - } - any = v; - return karabo::util::Types::VECTOR_STRING; - } - if (bp::extract(list0).check()) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = v; - return karabo::util::Types::VECTOR_HASH; - } - if (bp::extract(list0).check()) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = v; - return karabo::util::Types::VECTOR_HASH_POINTER; - } - if (bp::extract(list0).check()) { - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(obj[i]); - } - any = v; - return karabo::util::Types::VECTOR_SCHEMA; - } - } - if (hasattr(obj, "__name__")) { // python function - any = obj; - return karabo::util::Types::ANY; - } - throw KARABO_PYTHON_EXCEPTION("Python type can not be mapped into Hash"); - } - - bp::object Wrapper::fromNDArrayToPyArray(const karabo::util::NDArray& ndarray) { - using namespace karabo::util; - const Types::ReferenceType karaboType = ndarray.getType(); - const int typenum = Types::to(karaboType); - const size_t bytesPerItem = Types::to(karaboType); - const karabo::util::Dims shape = ndarray.getShape(); - const int nd = shape.rank(); - std::vector dims(nd, 0); - for (int i = 0; i < nd; ++i) { - dims[i] = shape.extentIn(i); - } - - const ByteArray& byteArray = ndarray.getByteArray(); - if (shape.size() * bytesPerItem > byteArray.second) { - throw KARABO_PARAMETER_EXCEPTION("Inconsistent NDArray: " + toString(byteArray.second) += - " are too few bytes for shape [" + toString(shape.toVector()) += - "] of " + Types::to(karaboType)); - } - - karabo::util::NDArray::DataPointer dataPtr(byteArray.first); - const boost::shared_ptr refHandler(new CppArrayRefHandler(dataPtr)); - bp::object pyRefHandler(refHandler); // Python reference count starts at 1 - void* data = reinterpret_cast(dataPtr.get()); - PyObject* pyobj = PyArray_SimpleNewFromData(nd, &dims[0], typenum, data); - PyArray_SetBaseObject(reinterpret_cast(pyobj), pyRefHandler.ptr()); - // PyArray_SetBaseObject steals a reference. Increase the refcount to protect bp::object::~object() - Py_INCREF(pyRefHandler.ptr()); - return bp::object(bp::handle<>(pyobj)); - } - - karabo::util::NDArray Wrapper::fromPyArrayToNDArray(PyArrayObject* arr) { - // Convert the array shape to a std::vector - npy_intp* pDims = PyArray_DIMS(arr); - std::vector dims; - for (int i = 0; i < PyArray_NDIM(arr); i++) { - dims.push_back(pDims[i]); - } - - // Get information about the stored type - PyArray_Descr* dtype = PyArray_DESCR(arr); - const int pyType = dtype->type_num; - const karabo::util::Types::ReferenceType krbType = karabo::util::Types::from(pyType); - - // Extract number of elements - const size_t nelems = static_cast(PyArray_SIZE(arr)); - - // Get a smart DataPointer object which points to the array's data - karabo::util::NDArray::DataPointer dataPtr; - - PyObject* arrBase = PyArray_BASE(arr); - - // Determine if the array data is owned by a C++ object - if (arrBase != NULL && arrBase != Py_None) { - bp::object base(bp::handle<>(bp::borrowed(arrBase))); - bp::extract maybeArrayRef(base); - if (maybeArrayRef.check()) { - const CppArrayRefHandler& arrayRef = maybeArrayRef(); - // The data already has an DataPointer object managing it. - dataPtr = arrayRef.getDataPtr(); - } - } - - // Array ref is still empty. Create a new ArrayData - if (!dataPtr) { - PyObject* pyobj = reinterpret_cast(arr); - // Get a contiguous copy of the array with the correct type (or just a reference if already compatible) - PyArrayObject* carr = reinterpret_cast( - PyArray_FROMANY(pyobj, pyType, KRB_NDARRAY_MIN_DIM, KRB_NDARRAY_MAX_DIM, NPY_ARRAY_C_CONTIGUOUS)); - if (carr != NULL) { - char* data = reinterpret_cast(PyArray_DATA(carr)); - const PyArrayRefHandler refHandler(carr); // Steals the reference to carr - // Create a new ArrayData which uses PyArrayRefHandler to manage the Python reference count - dataPtr = boost::shared_ptr(data, refHandler); - } - } - - if (!dataPtr) { - throw KARABO_PYTHON_EXCEPTION("Failed conversion of ndarray to C++ NDArray."); - } - - // Construct NDArray - return karabo::util::NDArray(dataPtr, krbType, nelems, karabo::util::Dims(dims)); - } - - - size_t Wrapper::numArgs(const bp::object& callable) { - size_t result = 0ul; - size_t numSelfArgs = 0ul; - - PyObject* function_object = NULL; - // We expect either - // * standalone function - // * member method - // * object with __call__ attribute - if (PyFunction_Check(callable.ptr())) { - function_object = callable.ptr(); - } else if (PyMethod_Check(callable.ptr())) { - function_object = PyMethod_Function(callable.ptr()); - numSelfArgs = 1ul; - } else if (Wrapper::hasattr(callable, "__call__")) { - bp::object call = callable.attr("__call__"); - if (PyFunction_Check(call.ptr())) { - function_object = call.ptr(); - } else if (PyMethod_Check(call.ptr())) { - function_object = PyMethod_Function(call.ptr()); - numSelfArgs = 1ul; - } else { - // For a functools.partial objects we end up here... - throw KARABO_PARAMETER_EXCEPTION( - "Attribute __call__ is neither function nor method, try to specify number of arguments."); - } - } else { - throw KARABO_PARAMETER_EXCEPTION("Cannot deduce number of arguments, please specify explicitely."); - } - PyCodeObject* pycode = reinterpret_cast(PyFunction_GetCode(function_object)); - if (pycode) { - // Note: co_argcount includes arguments with defaults, see nice figure from 'Hzzkygcs' at - // https://stackoverflow.com/questions/847936/how-can-i-find-the-number-of-arguments-of-a-python-function - result = pycode->co_argcount - numSelfArgs; // Subtract "self" if any - } else { // Can we get here? - throw KARABO_PARAMETER_EXCEPTION("Failed to access PyCode object to deduce number of arguments."); - } - - return result; - } - - - karabo::util::Hash Wrapper::deepCopy_r(const karabo::util::Hash& h) { - karabo::util::Hash r; - // iterate through all entries of the Hash. If the value of the Hash::Node at it - // is not of a Hash type we insert into our result Hash r, if not we recursivly - // call deepCopy_r to copy the internal structure - // We make sure to maintain attributes - for (karabo::util::Hash::const_iterator it = h.begin(); it != h.end(); ++it) { - if (it->getType() == karabo::util::Types::HASH) { - karabo::util::Hash::Node& n = r.set(it->getKey(), deepCopy_r(it->getValue())); - n.setAttributes(it->getAttributes()); - } else if (it->getType() == karabo::util::Types::VECTOR_HASH) { - const std::vector& v = it->getValue >(); - karabo::util::Hash::Node& n = r.set(it->getKey(), std::vector()); - std::vector& vc = n.getValue >(); - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(*vit)); - } - n.setAttributes(it->getAttributes()); - } else if (it->getType() == karabo::util::Types::HASH_POINTER) { - karabo::util::Hash::Node& n = - r.set(it->getKey(), deepCopy_r(*(it->getValue()))); - n.setAttributes(it->getAttributes()); - } else if (it->getType() == karabo::util::Types::VECTOR_HASH_POINTER) { - const std::vector& v = - it->getValue >(); - karabo::util::Hash::Node& n = r.set(it->getKey(), std::vector()); - std::vector& vc = n.getValue >(); - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(**vit)); - } - n.setAttributes(it->getAttributes()); - } else { // if no Hash type we do not need to recurse - r.setNode(it); - } - } - return r; - } - - bp::object Wrapper::deepCopyHashLike(const bp::object& obj) { - // we only check for Hash typed objects, which basically means obj - // contains a Hash::Node, a Hash, a vector of Hashes or pointers to Hashes - if (bp::extract(obj).check()) { - // Hash::Node case - check type information of the value and deep copy for aforementioned - // Hash types - const karabo::util::Hash::Node& node = bp::extract(obj); - if (node.getType() == karabo::util::Types::HASH) { - return bp::object(deepCopy_r(node.getValue())); - } else if (node.getType() == karabo::util::Types::VECTOR_HASH) { - const std::vector& v = node.getValue >(); - std::vector vc; - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(*vit)); - } - return bp::object(vc); - } else if (node.getType() == karabo::util::Types::HASH_POINTER) { - return bp::object(deepCopy_r(*node.getValue())); - } else if (node.getType() == karabo::util::Types::VECTOR_HASH_POINTER) { - const std::vector& v = - node.getValue >(); - std::vector vc; - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(**vit)); - } - return bp::object(vc); - } else { // if no Hash like object was found we just return the object - return obj; - } - // obj contains a Hash - } else if (bp::extract(obj).check()) { - const karabo::util::Hash& hash = bp::extract(obj); - return bp::object(deepCopy_r(hash)); - // obj contains a Hash::Pointer - } else if (bp::extract(obj).check()) { - const karabo::util::Hash::Pointer& hp = bp::extract(obj); - return bp::object(deepCopy_r(*hp)); - // obj contains a vector - } else if (bp::extract&>(obj).check()) { - const std::vector& v = bp::extract&>(obj); - std::vector vc; - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(*vit)); - } - return bp::object(vc); - // final scenario to deep copy: vector - } else if (bp::extract&>(obj).check()) { - const std::vector& v = - bp::extract&>(obj); - std::vector vc; - vc.reserve(v.size()); - for (auto vit = v.cbegin(); vit != v.cend(); ++vit) { - vc.push_back(deepCopy_r(**vit)); - } - return bp::object(vc); - } else { // nothing to deep-copy - return obj; - } - } - - void HandlerWrapAny1::operator()(const boost::any& a1) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(Wrapper::toObject(a1)); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - void HandlerWrapAny2::operator()(const boost::any& a1, const boost::any& a2) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(Wrapper::toObject(a1), Wrapper::toObject(a2)); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - void HandlerWrapAny3::operator()(const boost::any& a1, const boost::any& a2, const boost::any& a3) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(Wrapper::toObject(a1), Wrapper::toObject(a2), Wrapper::toObject(a3)); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - void HandlerWrapAny4::operator()(const boost::any& a1, const boost::any& a2, const boost::any& a3, - const boost::any& a4) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(Wrapper::toObject(a1), Wrapper::toObject(a2), Wrapper::toObject(a3), - Wrapper::toObject(a4)); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - void HandlerWrapVullVull::operator()(const std::vector& v1, - const std::vector& v2) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - (*m_handler)(Wrapper::fromStdVectorToPyList(v1), Wrapper::fromStdVectorToPyList(v2)); - } - } catch (const bp::error_already_set& e) { - karathon::detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - - std::tuple getPythonExceptionStrings() { - // Fetch parameters of error indicator ... the error indicator is getting cleared! - // ... the new references returned! - PyObject *pexceptType, *pexception, *ptraceback; - - PyErr_Fetch(&pexceptType, &pexception, &ptraceback); // ref count incremented - PyErr_NormalizeException(&pexceptType, &pexception, &ptraceback); - - std::string pythonErrorMessage; - std::string pythonErrorDetails; - - if (pexceptType && pexception && ptraceback) { - // Try to extract full traceback - PyObject* moduleTraceback = PyImport_ImportModule("traceback"); - if (moduleTraceback != 0) { - // Letter "O" in format string denotes conversion from Object ... 3 arguments - PyObject* plist = PyObject_CallMethod(moduleTraceback, "format_exception", "OOO", pexceptType, - pexception, ptraceback); - if (plist) { - // "format_exception" returns list of strings - Py_ssize_t size = PyList_Size(plist); // > 0, see doc of "format_exception"/"print_exception" - for (Py_ssize_t i = 0; i < size - 1; ++i) { - // All but last line in list is traceback - PyObject* pstrItem = PyList_GetItem(plist, i); // this "borrowed reference" - no decref! - pythonErrorDetails.append(PyUnicode_AsUTF8(pstrItem)); - } - // Last line is type and message - PyObject* pstrItem = PyList_GetItem(plist, size - 1); // this "borrowed reference" - no decref! - pythonErrorMessage = PyUnicode_AsUTF8(pstrItem); - Py_DECREF(plist); - } - Py_DECREF(moduleTraceback); - } else { - PyObject* pythonRepr = PyObject_Repr(pexception); // apply repr() - pythonErrorMessage.assign(PyUnicode_AsUTF8(pythonRepr)); - Py_DECREF(pythonRepr); - } - } // else there is no exception, so keep pythonErrorMessage empty - - // we reset it for later processing - PyErr_Restore(pexceptType, pexception, ptraceback); // ref count decremented - PyErr_Clear(); - // Remove trailing newline - boost::algorithm::trim_right(pythonErrorMessage); - boost::algorithm::trim_right(pythonErrorDetails); - - return std::make_tuple(pythonErrorMessage, pythonErrorDetails); - } - - namespace detail { - void treatError_already_set(const bp::object& handler, const char* where) { - std::string errStr, errDetails; - if (PyErr_Occurred()) { - std::tie(errStr, errDetails) = getPythonExceptionStrings(); - } - const std::string funcName(Wrapper::hasattr(handler, "__name__") - ? std::string(bp::extract(handler.attr("__name__"))) - : std::string()); // e.g. 'partial' does not provide __name__ - std::ostringstream oss; - oss << "Error in "; - if (funcName.empty()) { - oss << " python handler for '" << (where ? where : "undefined") << "'"; - } else { - oss << "'" << funcName << "'"; - } - oss << ": " << errStr; - errStr = oss.str(); - std::cerr << '\n' << errStr << '\n' << errDetails << std::endl; - throw KARABO_PYTHON_EXCEPTION2(errStr, errDetails); - } - } // namespace detail -} // namespace karathon diff --git a/src/karathon/Wrapper.hh b/src/karathon/Wrapper.hh deleted file mode 100644 index 4457c60d85..0000000000 --- a/src/karathon/Wrapper.hh +++ /dev/null @@ -1,881 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ -/* - * File: Wrapper.hh - * Author: esenov - * - * Created on March 17, 2013, 10:52 PM - */ - -#ifndef WRAPPER_HH -#define WRAPPER_HH - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "FromNumpy.hh" -#include "ToNumpy.hh" - -#define PY_ARRAY_UNIQUE_SYMBOL karabo_ARRAY_API -#define KRB_NDARRAY_MIN_DIM 1 -#define KRB_NDARRAY_MAX_DIM 6 - -#define NO_IMPORT_ARRAY -#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION -#include - -#include "ScopedGILAcquire.hh" - -namespace bp = boost::python; - -namespace karathon { - - class PyTypes { - public: - enum ReferenceType { - - BOOL = karabo::util::Types::BOOL, // boolean - VECTOR_BOOL = karabo::util::Types::VECTOR_BOOL, // std::vector - - CHAR = karabo::util::Types::CHAR, // char - VECTOR_CHAR = karabo::util::Types::VECTOR_CHAR, // std::vector - INT8 = karabo::util::Types::INT8, // signed char - VECTOR_INT8 = karabo::util::Types::VECTOR_INT8, // std::vector - UINT8 = karabo::util::Types::UINT8, // unsigned char - VECTOR_UINT8 = karabo::util::Types::VECTOR_UINT8, // std::vector - - INT16 = karabo::util::Types::INT16, // signed short - VECTOR_INT16 = karabo::util::Types::VECTOR_INT16, // std::vector - UINT16 = karabo::util::Types::UINT16, // unsigned short - VECTOR_UINT16 = karabo::util::Types::VECTOR_UINT16, // std::vector - - INT32 = karabo::util::Types::INT32, // signed int - VECTOR_INT32 = karabo::util::Types::VECTOR_INT32, // std::vector - UINT32 = karabo::util::Types::UINT32, // unsigned int - VECTOR_UINT32 = karabo::util::Types::VECTOR_UINT32, // std::vector - - INT64 = karabo::util::Types::INT64, // signed long long - VECTOR_INT64 = karabo::util::Types::VECTOR_INT64, // std::vector - UINT64 = karabo::util::Types::UINT64, // unsigned long long - VECTOR_UINT64 = karabo::util::Types::VECTOR_UINT64, // std::vector - - FLOAT = karabo::util::Types::FLOAT, // float - VECTOR_FLOAT = karabo::util::Types::VECTOR_FLOAT, // std::vector - - DOUBLE = karabo::util::Types::DOUBLE, // double - VECTOR_DOUBLE = karabo::util::Types::VECTOR_DOUBLE, // std::vector - - COMPLEX_FLOAT = karabo::util::Types::COMPLEX_FLOAT, // std::complex - VECTOR_COMPLEX_FLOAT = karabo::util::Types::VECTOR_COMPLEX_FLOAT, // std::vector - - COMPLEX_DOUBLE = karabo::util::Types::COMPLEX_DOUBLE, // std::complex - VECTOR_COMPLEX_DOUBLE = karabo::util::Types::VECTOR_COMPLEX_DOUBLE, // std::vector - - STRING = karabo::util::Types::STRING, // std::string - VECTOR_STRING = karabo::util::Types::VECTOR_STRING, // std::vector - - HASH = karabo::util::Types::HASH, // Hash - VECTOR_HASH = karabo::util::Types::VECTOR_HASH, // std::vector - - PTR_BOOL = karabo::util::Types::PTR_BOOL, - PTR_CHAR = karabo::util::Types::PTR_CHAR, - PTR_INT8 = karabo::util::Types::PTR_INT8, - PTR_UINT8 = karabo::util::Types::PTR_UINT8, - PTR_INT16 = karabo::util::Types::PTR_INT16, - PTR_UINT16 = karabo::util::Types::PTR_UINT16, - PTR_INT32 = karabo::util::Types::PTR_INT32, - PTR_UINT32 = karabo::util::Types::PTR_UINT32, - PTR_INT64 = karabo::util::Types::PTR_INT64, - PTR_UINT64 = karabo::util::Types::PTR_UINT64, - PTR_FLOAT = karabo::util::Types::PTR_FLOAT, - PTR_DOUBLE = karabo::util::Types::PTR_DOUBLE, - PTR_COMPLEX_FLOAT = karabo::util::Types::PTR_COMPLEX_FLOAT, - PTR_COMPLEX_DOUBLE = karabo::util::Types::PTR_COMPLEX_DOUBLE, - PTR_STRING = karabo::util::Types::PTR_STRING, - - SCHEMA = karabo::util::Types::SCHEMA, // Schema - - ANY = karabo::util::Types::ANY, // unspecified type - NONE = karabo::util::Types::NONE, // CppNone type used during serialization/de-serialization - VECTOR_NONE = karabo::util::Types::VECTOR_NONE, - - UNKNOWN = karabo::util::Types::UNKNOWN, // unknown type - SIMPLE = karabo::util::Types::SIMPLE, - SEQUENCE = karabo::util::Types::SEQUENCE, - POINTER = karabo::util::Types::POINTER, - - HASH_POINTER = karabo::util::Types::HASH_POINTER, - VECTOR_HASH_POINTER = karabo::util::Types::VECTOR_HASH_POINTER, - LAST_CPP_TYPE = karabo::util::Types::VECTOR_HASH_POINTER + 1, - PYTHON_DEFAULT, // global switch: treat std::vector as bp::list - NUMPY_DEFAULT, // global switch: treat std::vector as ndarray - }; - - static const ReferenceType from(const karabo::util::Types::ReferenceType& input) { - switch (input) { - case karabo::util::Types::BOOL: - return BOOL; - case karabo::util::Types::VECTOR_BOOL: - return VECTOR_BOOL; - case karabo::util::Types::CHAR: - return CHAR; - case karabo::util::Types::VECTOR_CHAR: - return VECTOR_CHAR; - case karabo::util::Types::INT8: - return INT8; - case karabo::util::Types::VECTOR_INT8: - return VECTOR_INT8; - case karabo::util::Types::UINT8: - return UINT8; - case karabo::util::Types::VECTOR_UINT8: - return VECTOR_UINT8; - case karabo::util::Types::INT16: - return INT16; - case karabo::util::Types::VECTOR_INT16: - return VECTOR_INT16; - case karabo::util::Types::UINT16: - return UINT16; - case karabo::util::Types::VECTOR_UINT16: - return VECTOR_UINT16; - case karabo::util::Types::INT32: - return INT32; - case karabo::util::Types::VECTOR_INT32: - return VECTOR_INT32; - case karabo::util::Types::UINT32: - return UINT32; - case karabo::util::Types::VECTOR_UINT32: - return VECTOR_UINT32; - case karabo::util::Types::INT64: - return INT64; - case karabo::util::Types::VECTOR_INT64: - return VECTOR_INT64; - case karabo::util::Types::UINT64: - return UINT64; - case karabo::util::Types::VECTOR_UINT64: - return VECTOR_UINT64; - case karabo::util::Types::FLOAT: - return FLOAT; - case karabo::util::Types::VECTOR_FLOAT: - return VECTOR_FLOAT; - case karabo::util::Types::DOUBLE: - return DOUBLE; - case karabo::util::Types::VECTOR_DOUBLE: - return VECTOR_DOUBLE; - case karabo::util::Types::COMPLEX_FLOAT: - return COMPLEX_FLOAT; - case karabo::util::Types::VECTOR_COMPLEX_FLOAT: - return VECTOR_COMPLEX_FLOAT; - case karabo::util::Types::COMPLEX_DOUBLE: - return COMPLEX_DOUBLE; - case karabo::util::Types::VECTOR_COMPLEX_DOUBLE: - return VECTOR_COMPLEX_DOUBLE; - case karabo::util::Types::STRING: - return STRING; - case karabo::util::Types::VECTOR_STRING: - return VECTOR_STRING; - case karabo::util::Types::HASH: - return HASH; - case karabo::util::Types::VECTOR_HASH: - return VECTOR_HASH; - case karabo::util::Types::PTR_BOOL: - return PTR_BOOL; - case karabo::util::Types::PTR_CHAR: - return PTR_CHAR; - case karabo::util::Types::PTR_INT8: - return PTR_INT8; - case karabo::util::Types::PTR_UINT8: - return PTR_UINT8; - case karabo::util::Types::PTR_INT16: - return PTR_INT16; - case karabo::util::Types::PTR_UINT16: - return PTR_UINT16; - case karabo::util::Types::PTR_INT32: - return PTR_INT32; - case karabo::util::Types::PTR_UINT32: - return PTR_UINT32; - case karabo::util::Types::PTR_INT64: - return PTR_INT64; - case karabo::util::Types::PTR_UINT64: - return PTR_UINT64; - case karabo::util::Types::PTR_FLOAT: - return PTR_FLOAT; - case karabo::util::Types::PTR_DOUBLE: - return PTR_DOUBLE; - case karabo::util::Types::PTR_COMPLEX_FLOAT: - return PTR_COMPLEX_FLOAT; - case karabo::util::Types::PTR_COMPLEX_DOUBLE: - return PTR_COMPLEX_DOUBLE; - case karabo::util::Types::PTR_STRING: - return PTR_STRING; - case karabo::util::Types::SCHEMA: - return SCHEMA; - case karabo::util::Types::ANY: - return ANY; - case karabo::util::Types::NONE: - return NONE; - case karabo::util::Types::VECTOR_NONE: - return VECTOR_NONE; - case karabo::util::Types::UNKNOWN: - return UNKNOWN; - case karabo::util::Types::SIMPLE: - return SIMPLE; - case karabo::util::Types::SEQUENCE: - return SEQUENCE; - case karabo::util::Types::POINTER: - return POINTER; - case karabo::util::Types::HASH_POINTER: - return HASH_POINTER; - case karabo::util::Types::VECTOR_HASH_POINTER: - return VECTOR_HASH_POINTER; - default: - throw KARABO_PYTHON_EXCEPTION("Unknown type encountered while converting from Types to PyTypes."); - } - } - - static const karabo::util::Types::ReferenceType to(const ReferenceType& input) { - switch (input) { - case BOOL: - return karabo::util::Types::BOOL; - case VECTOR_BOOL: - return karabo::util::Types::VECTOR_BOOL; - case CHAR: - return karabo::util::Types::CHAR; - case VECTOR_CHAR: - return karabo::util::Types::VECTOR_CHAR; - case INT8: - return karabo::util::Types::INT8; - case VECTOR_INT8: - return karabo::util::Types::VECTOR_INT8; - case UINT8: - return karabo::util::Types::UINT8; - case VECTOR_UINT8: - return karabo::util::Types::VECTOR_UINT8; - case INT16: - return karabo::util::Types::INT16; - case VECTOR_INT16: - return karabo::util::Types::VECTOR_INT16; - case UINT16: - return karabo::util::Types::UINT16; - case VECTOR_UINT16: - return karabo::util::Types::VECTOR_UINT16; - case INT32: - return karabo::util::Types::INT32; - case VECTOR_INT32: - return karabo::util::Types::VECTOR_INT32; - case UINT32: - return karabo::util::Types::UINT32; - case VECTOR_UINT32: - return karabo::util::Types::VECTOR_UINT32; - case INT64: - return karabo::util::Types::INT64; - case VECTOR_INT64: - return karabo::util::Types::VECTOR_INT64; - case UINT64: - return karabo::util::Types::UINT64; - case VECTOR_UINT64: - return karabo::util::Types::VECTOR_UINT64; - case FLOAT: - return karabo::util::Types::FLOAT; - case VECTOR_FLOAT: - return karabo::util::Types::VECTOR_FLOAT; - case DOUBLE: - return karabo::util::Types::DOUBLE; - case VECTOR_DOUBLE: - return karabo::util::Types::VECTOR_DOUBLE; - case COMPLEX_FLOAT: - return karabo::util::Types::COMPLEX_FLOAT; - case VECTOR_COMPLEX_FLOAT: - return karabo::util::Types::VECTOR_COMPLEX_FLOAT; - case COMPLEX_DOUBLE: - return karabo::util::Types::COMPLEX_DOUBLE; - case VECTOR_COMPLEX_DOUBLE: - return karabo::util::Types::VECTOR_COMPLEX_DOUBLE; - case STRING: - return karabo::util::Types::STRING; - case VECTOR_STRING: - return karabo::util::Types::VECTOR_STRING; - case HASH: - return karabo::util::Types::HASH; - case VECTOR_HASH: - return karabo::util::Types::VECTOR_HASH; - case PTR_BOOL: - return karabo::util::Types::PTR_BOOL; - case PTR_CHAR: - return karabo::util::Types::PTR_CHAR; - case PTR_INT8: - return karabo::util::Types::PTR_INT8; - case PTR_UINT8: - return karabo::util::Types::PTR_UINT8; - case PTR_INT16: - return karabo::util::Types::PTR_INT16; - case PTR_UINT16: - return karabo::util::Types::PTR_UINT16; - case PTR_INT32: - return karabo::util::Types::PTR_INT32; - case PTR_UINT32: - return karabo::util::Types::PTR_UINT32; - case PTR_INT64: - return karabo::util::Types::PTR_INT64; - case PTR_UINT64: - return karabo::util::Types::PTR_UINT64; - case PTR_FLOAT: - return karabo::util::Types::PTR_FLOAT; - case PTR_DOUBLE: - return karabo::util::Types::PTR_DOUBLE; - case PTR_COMPLEX_FLOAT: - return karabo::util::Types::PTR_COMPLEX_FLOAT; - case PTR_COMPLEX_DOUBLE: - return karabo::util::Types::PTR_COMPLEX_DOUBLE; - case PTR_STRING: - return karabo::util::Types::PTR_STRING; - case SCHEMA: - return karabo::util::Types::SCHEMA; - case ANY: - return karabo::util::Types::ANY; - case NONE: - return karabo::util::Types::NONE; - case VECTOR_NONE: - return karabo::util::Types::VECTOR_NONE; - case UNKNOWN: - return karabo::util::Types::UNKNOWN; - case SIMPLE: - return karabo::util::Types::SIMPLE; - case SEQUENCE: - return karabo::util::Types::SEQUENCE; - case POINTER: - return karabo::util::Types::POINTER; - case HASH_POINTER: - return karabo::util::Types::HASH_POINTER; - case VECTOR_HASH_POINTER: - return karabo::util::Types::VECTOR_HASH_POINTER; - default: - throw KARABO_PYTHON_EXCEPTION( - "Unsupported type encountered while converting from PyTypes to Types."); - } - } - - static const ReferenceType category(int type) { - return from(karabo::util::Types::category(type)); - } - }; - - // Handler class for arrays originating in C++ code - - class CppArrayRefHandler { - private: - karabo::util::NDArray::DataPointer m_dataPtr; - - public: - explicit CppArrayRefHandler(const karabo::util::NDArray::DataPointer& dataPtr) : m_dataPtr(dataPtr) {} - - karabo::util::NDArray::DataPointer getDataPtr() const { - return m_dataPtr; - } - }; - - // Handler class for arrays originating in Python code - - class PyArrayRefHandler { - PyArrayObject* m_arrayRef; - - public: - explicit PyArrayRefHandler(PyArrayObject* obj) : m_arrayRef(obj) {} - - void operator()(const char*) { - Py_DECREF(m_arrayRef); - } - }; - - namespace detail { - /// Helper when catching Python exceptions - void treatError_already_set(const bp::object& handler, const char* where); - } // namespace detail - - struct Wrapper { - struct null_deleter { - void operator()(void const*) const {} - }; - - static bool hasattr(bp::object obj, const std::string& attrName) { - // NOTE: There seems to be different implementations of the Python C-API around - // Some use a char* some other a const char* -> char* is the always compiling alternative - return PyObject_HasAttrString(obj.ptr(), const_cast(attrName.c_str())); - } - - template - static bp::tuple fromStdPairToPyTuple(const std::pair& p) { - return bp::make_tuple(p.first, p.second); - } - - template - static bp::list fromStdVectorToPyList(const std::vector& v) { - bp::list pylist; - for (size_t i = 0; i < v.size(); i++) pylist.append(bp::object(v[i])); - return pylist; - } - - template - static bp::list fromStdVectorToPyList(const std::vector >& v) { - bp::list pylist; - for (size_t i = 0; i < v.size(); i++) pylist.append(bp::make_tuple(v[i].first, v[i].second)); - return pylist; - } - - template - static bp::tuple fromStdVectorToPyTuple(const std::vector& v) { - return bp::tuple(fromStdVectorToPyList(v)); - } - - static bp::list fromStdVectorToPyHashList(const std::vector& v) { - bp::object it = bp::iterator >(); - bp::object iter = it(v); - bp::list l(iter); - return l; - } - - static bp::object fromStdVectorToPyBytes(const std::vector& v) { - const char* data = &v[0]; - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyBytes_FromStringAndSize(data, size))); - } - - static bp::object fromStdVectorToPyBytes(const std::vector& v) { - const char* data = reinterpret_cast(&v[0]); - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyBytes_FromStringAndSize(data, size))); - } - - static bp::object fromStdVectorToPyBytes(const std::vector& v) { - const char* data = reinterpret_cast(&v[0]); - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyBytes_FromStringAndSize(data, size))); - } - - static bp::object fromStdVectorToPyByteArray(const std::vector& v) { - const char* data = &v[0]; - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyByteArray_FromStringAndSize(data, size))); - } - - static bp::object fromStdVectorToPyByteArray(const std::vector& v) { - const char* data = reinterpret_cast(&v[0]); - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyByteArray_FromStringAndSize(data, size))); - } - - static bp::object fromStdVectorToPyByteArray(const std::vector& v) { - const char* data = reinterpret_cast(&v[0]); - Py_ssize_t size = v.size(); - return bp::object(bp::handle<>(PyByteArray_FromStringAndSize(data, size))); - } - - static bp::str fromStdVectorToPyStr(const std::vector& v) { - return bp::str(&v[0], v.size()); - } - - static bp::str fromStdVectorToPyStr(const std::vector& v) { - return bp::str(reinterpret_cast(&v[0]), v.size()); - } - - static bp::str fromStdVectorToPyStr(const std::vector& v) { - return bp::str(reinterpret_cast(&v[0]), v.size()); - } - - template - static std::vector fromPyListToStdVector(const bp::object& obj) { - const bp::list& lst = bp::extract(obj); - bp::ssize_t size = bp::len(lst); - - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(lst[i]); - } - return v; - } - - template - static std::vector fromPyTupleToStdVector(const bp::object& obj) { - const bp::tuple& tpl = bp::extract(obj); - bp::ssize_t size = bp::len(tpl); - - std::vector v(size); - for (bp::ssize_t i = 0; i < size; ++i) { - v[i] = bp::extract(tpl[i]); - } - return v; - } - - /** - * Convert a Python iterable containing objects convertible to T to C++ container CONT. - * The container type must be constructable from an iterator range. - * - * Example: - * const bp::object& obj = ...; // list, tuple, dictionary [where you get the keys],... - * const std::set setOfInt = fromPyIterableToContainer(o); - * - * @param obj the Python object - * @return C++ container of type CONT - */ - template > class CONT = std::vector> - static CONT fromPyIterableToCppContainer(const bp::object& obj) { - bp::stl_input_iterator begin(obj), end; - return CONT(begin, end); - } - - static bp::object toObject(const boost::any& operand, bool numpyFlag = false); - - static bp::object toCustomObject(karabo::util::Hash::Node& node); - - /** - * Convert obj to desired IntegerType which should be unsigned short, int, long long, etc. - * - * @param obj must be a Python object representing an integer - if not, a karabo::util::CastException is thrown - * @return the properly typed integer value - */ - template - static IntegerType toInteger(const bp::object& obj); - - static karabo::util::Types::ReferenceType toAny(const bp::object& operand, boost::any& any); - - static bp::object fromStdVectorToPyListNone(const std::vector& v) { - bp::list pylist; - for (size_t i = 0; i < v.size(); i++) pylist.append(bp::object()); - return pylist; - } - - template - static bp::object fromStdVectorToPyArray(const std::vector& v, bool numpyFlag = false) { - return fromStdVectorToPyList(v); - } - - static karabo::util::NDArray fromPyArrayToNDArray(PyArrayObject* arr); - - static bp::object fromNDArrayToPyArray(const karabo::util::NDArray& ndarray); - - /** - * How many non-keyword arguments does 'callable' expect? - * - * Works for free functions, member methods and objects with simple __call__ method (even with @staticmethod), - * but not for functools.partial objects. - * - */ - static size_t numArgs(const bp::object& callable); - - /** - * Inner recursive copier for deepCopy - * @param h - * @return - */ - static karabo::util::Hash deepCopy_r(const karabo::util::Hash& h); - - /** - * A recursively copying function, that guarantees that no references or - * pointers remain in a Hash. Use if correct object lifetime management - * when passing to python cannot be guaranteed. - * @param obj potentially containing Hash reference or pointer as well as vectors thereof to be deep copied - * @return a deep copy of obj - */ - static bp::object deepCopyHashLike(const bp::object& obj); - - /** - * A proxy around a Python handler to be called with an arbitrary number of arguments - * - * @param handler A callable Python object - * @param which A C-string used to better identify the point of failure in case the Python - * code throws an exception - * @param args An arbitrary number of arguments passed to the handler - each has to be a valid - * argument to the constructor of the boost Python object. - */ - template - static void proxyHandler(const bp::object& handler, const char* which, const Args&... args) { - ScopedGILAcquire gil; - try { - if (handler) { - // Just call handler with individually unpacked arguments: - handler(bp::object(args)...); - } - } catch (const bp::error_already_set& e) { - detail::treatError_already_set(handler, which); - } catch (...) { - KARABO_RETHROW - } - } - }; - - /** A functor to wrap a Python handler such that - * - handler is called with GIL, - * - exceptions in handler calls are properly treated and forwarded, - * - handler's destructor is called under GIL. - * - * Template types are the C++ arguments to be passed to the handler. - * Caveat: - * For types where the automatic conversion does not work (e.g. boost::any and std:vector<..>,) - * a specialised implementation for the operator() might be needed, using e.g. the - * Wrapper::toObject or Wrapper::from[...]ToPy[...] methods for conversion, see e.g. class HandlerWrapAny1. - */ - template - class HandlerWrap { - public: - /** - * Construct a wrapper for a Python handler whose return value is ignored. - * - * `Args` are the C++ arguments that the wrapper is expected to be called with. - * - * @param handler the Python callable to wrap - * @param where a C string identifying which handler is wrapped, - * for debugging only, i.e. used if a call to the handler raises an exception - */ - HandlerWrap(const bp::object& handler, char const* const where) - : m_handler(std::make_shared(handler)), // new object on the heap to control its destruction - m_where(where) {} - - - ~HandlerWrap() { - // Ensure that destructor of Python handler object is called with GIL - ScopedGILAcquire gil; - m_handler.reset(); - } - - - void operator()(Args... args) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - // Just call handler with individually unpacked arguments: - (*m_handler)(bp::object(std::forward(args))...); - } - } catch (bp::error_already_set& e) { - detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - protected: // not private - needed by HandlerWrapExtra, HandlerWrapAny and InputChannelWrap::DataHandlerWrap - std::shared_ptr m_handler; - char const* const m_where; - }; - - /** - * Specialisation of HandlerWrap that stores an extra C++ object and - * passes it as second argument to the Python handler - * - * The arguments are converted to bp::object before passed to the Python handler. - */ - template - class HandlerWrapExtra : public HandlerWrap { - public: - HandlerWrapExtra(const bp::object& handler, char const* const where, const ExtraArg& extra) - : HandlerWrap(handler, where), m_extraArg(extra) {} - - // This definition resolves serfault issue while destroying m_extraArg == channel (Channel::Pointer type) - // since the destruction is done under the GIL. Note that in karabind case this is not needed and this is - // considered here (boost::python?) as a hack. - ~HandlerWrapExtra() { - ScopedGILAcquire gil; - m_extraArg = nullptr; - } - - void operator()(FirstArg first, Args... args) const { - ScopedGILAcquire gil; - try { - if (*m_handler) { - // Call handler with individually unpacked arguments, but put the extra one as second: - (*m_handler)(bp::object(std::move(first)), bp::object(m_extraArg), - bp::object(std::forward(args))...); - } - } catch (bp::error_already_set& e) { - detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - } - - private: - ExtraArg m_extraArg; - // Make (non-private) base class members available. Needed since 'C++ doesn’t consider superclass templates for - // name resolution' (see - // https://stackoverflow.com/questions/4010281/accessing-protected-members-of-superclass-in-c-with-templates): - using HandlerWrap::m_handler; - using HandlerWrap::m_where; - }; - - template - class ReturnHandlerWrap { - public: - /** - * Construct a wrapper for a Python handler whose return value is of interest. - * The return value of the handler must be castable to 'Ret'. - * @param handler the Python callable to wrap - * @param where a C string identifying which handler is wrapped, - * for debugging only, i.e. used if a call to the handler raises an exception - */ - ReturnHandlerWrap(const bp::object& handler, char const* const where) - : m_handler(std::make_shared(handler)), // new object on the heap to control its destruction - m_where(where) {} - - - ~ReturnHandlerWrap() { - // Ensure that destructor of Python handler object is called with GIL - ScopedGILAcquire gil; - m_handler.reset(); - } - - - Ret operator()(Args... args) const { - ScopedGILAcquire gil; - bp::object pyResult; - try { - if (*m_handler) { - // Just call handler with individually unpacked arguments - pyResult = (*m_handler)(bp::object(args)...); // std::forward(args)? - } - } catch (bp::error_already_set& e) { - detail::treatError_already_set(*m_handler, m_where); - } catch (...) { - KARABO_RETHROW - } - return bp::extract(pyResult); - } - - private: // may become protected if a derived class needs to overwrite operator() - std::shared_ptr m_handler; - char const* const m_where; - }; - - /** - * Specialisation of HandlerWrap for one boost::any argument - * - * The argument is converted to boost::object before passed to the Python handler. - */ - class HandlerWrapAny1 : public HandlerWrap { - public: - HandlerWrapAny1(const bp::object& handler, char const* const where) - : HandlerWrap(handler, where) {} - - void operator()(const boost::any& a1) const; - }; - - /** - * Specialisation of HandlerWrap for two boost::any arguments - * - * The arguments are converted to boost::object before passed to the Python handler. - */ - class HandlerWrapAny2 : public HandlerWrap { - public: - HandlerWrapAny2(const bp::object& handler, char const* const where) - : HandlerWrap(handler, where) {} - - void operator()(const boost::any& a1, const boost::any& a2) const; - }; - - /** - * Specialisation of HandlerWrap for three boost::any arguments - * - * The arguments are converted to boost::object before passed to the Python handler. - */ - class HandlerWrapAny3 : public HandlerWrap { - public: - HandlerWrapAny3(const bp::object& handler, char const* const where) - : HandlerWrap(handler, where) {} - - void operator()(const boost::any& a1, const boost::any& a2, const boost::any& a3) const; - }; - - /** - * Specialisation of HandlerWrap for four boost::any arguments - * - * The arguments are converted to boost::object before passed to the Python handler. - */ - class HandlerWrapAny4 - : public HandlerWrap { - public: - HandlerWrapAny4(const bp::object& handler, char const* const where) - : HandlerWrap(handler, where) {} - - void operator()(const boost::any& a1, const boost::any& a2, const boost::any& a3, const boost::any& a4) const; - }; - - /** - * Specialisation of HandlerWrap for two vector arguments - * - * The arguments are converted to boost::object before passed to the Python handler. - */ - class HandlerWrapVullVull - : public HandlerWrap&, const std::vector&> { - public: - HandlerWrapVullVull(const bp::object& handler, char const* const where) - : HandlerWrap&, const std::vector&>(handler, - where) {} - - void operator()(const std::vector& v1, const std::vector& v2) const; - }; - - /** - * Provide exception text and details (i.e. traceback) - * To be called from within a "catch (const bp::error_already_set& e)" block. - * - * @return tuple of two strings: - * - first is (Python) exception text, - * - second the multiline traceback like from traceback.print_exception (skipping last line) - */ - std::tuple getPythonExceptionStrings(); - - // Specializations - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - template <> - bp::object Wrapper::fromStdVectorToPyArray(const std::vector& v, bool numpyFlag); - - // Implementations of template code - template - IntegerType Wrapper::toInteger(const bp::object& obj) { - if (PyLong_Check(obj.ptr())) { - const PY_LONG_LONG value = PyLong_AsLongLong(obj.ptr()); - return static_cast(value); - } else { - throw KARABO_CAST_EXCEPTION("Cannot cast Python object to '" + std::string(typeid(IntegerType).name()) += - "'"); - return static_cast(0); // please the compiler - } - } -} // namespace karathon - -#endif /* WRAPPER_HH */ diff --git a/src/karathon/karathon.cc b/src/karathon/karathon.cc deleted file mode 100644 index cab6cbd01c..0000000000 --- a/src/karathon/karathon.cc +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Author: , - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -#define PY_ARRAY_UNIQUE_SYMBOL karabo_ARRAY_API -#include - -#include "ScopedGILRelease.hh" - -namespace bp = boost::python; -// util -void exportPyUtilHash(); -void exportPyUtilSchema(); -void exportPyUtilClassInfo(); -void exportPyUtilTrainstamp(); -void exportPyUtilDateTimeString(); -void exportPyUtilEpochstamp(); -void exportPyUtilException(); -void exportPyUtilTimestamp(); -void exportPyUtilTimeDuration(); -void exportPyUtilDims(); -void exportPyUtilNDArray(); -void exportPyUtilRollingWindowStatistics(); -void exportPyUtilStateElement(); -void exportPyUtilAlarmConditionElement(); -void exportPyUtilJsonToHashParser(); - -// io -void exportPyIo(); -void exportPyIoFileTools(); -template -void exportPyIOFileTools1(); -template -void exportPyIoOutput(); -template -void exportPyIoInput(); -template -void exportPyIoTextSerializer(); -template -void exportPyIoBinarySerializer(); - -// xms -void exportPyXmsInputOutputChannel(); -void exportPyXmsSignalSlotable(); -void exportPyXmsSlotElement(); - -// core -void exportPyCoreDeviceClient(); -void exportPyCoreLock(); - -// log -void exportPyLogLogger(); - -// net -void exportp2p(); - -// utilities -void exportPyKarathonTestUtilities(); - - -void* convert_to_cstring(PyObject* obj) { - const void* ret = PyUnicode_AsUTF8(obj); - if (!ret) PyErr_Clear(); - - return const_cast(ret); -} - - -void* convertible_string(PyObject* obj) { - if (PyUnicode_Check(obj)) return const_cast(""); - else return 0; -} - - -void construct_string(PyObject* obj, boost::python::converter::rvalue_from_python_stage1_data* data) { - void* storage = ((boost::python::converter::rvalue_from_python_storage*)data)->storage.bytes; - Py_ssize_t size; - const char* str = PyUnicode_AsUTF8AndSize(obj, &size); - new (storage) std::string(str, size); - data->convertible = storage; -} - - -void* import_numpy() { - // init Array C-API - import_array(); - return 0; -} - - -BOOST_PYTHON_MODULE(karathon) { - PyEval_InitThreads(); - import_numpy(); - - // util - exportPyUtilHash(); - exportPyUtilClassInfo(); - exportPyUtilTrainstamp(); - exportPyUtilEpochstamp(); - exportPyUtilException(); - exportPyUtilTimestamp(); - exportPyUtilTimeDuration(); - exportPyUtilDims(); - exportPyUtilSchema(); - exportPyUtilDateTimeString(); - exportPyUtilRollingWindowStatistics(); - exportPyUtilStateElement(); - exportPyUtilAlarmConditionElement(); - exportPyUtilNDArray(); - exportPyUtilJsonToHashParser(); - - // io - exportPyIo(); - exportPyIoFileTools(); - exportPyIOFileTools1(); - exportPyIOFileTools1(); - - exportPyIoOutput(); - exportPyIoOutput(); - - exportPyIoInput(); - exportPyIoInput(); - - exportPyIoTextSerializer(); - exportPyIoTextSerializer(); - - exportPyIoBinarySerializer(); - exportPyIoBinarySerializer(); - - - // xms - exportPyXmsInputOutputChannel(); - exportPyXmsSignalSlotable(); - exportPyXmsSlotElement(); - - // core - exportPyCoreLock(); - exportPyCoreDeviceClient(); - - // log - exportPyLogLogger(); - - // net - exportp2p(); - - // utilities - exportPyKarathonTestUtilities(); - - boost::python::converter::registry::insert(convert_to_cstring, boost::python::type_id(), - &boost::python::converter::wrap_pytype<&PyUnicode_Type>::get_pytype); - boost::python::converter::registry::insert(convertible_string, construct_string, - boost::python::type_id(), - &boost::python::converter::wrap_pytype<&PyUnicode_Type>::get_pytype); -} diff --git a/src/karathon/karathon_test.cc b/src/karathon/karathon_test.cc deleted file mode 100644 index 2574194f71..0000000000 --- a/src/karathon/karathon_test.cc +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Author: CONTROLS DEV group - * - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include -#include - -#include "Wrapper.hh" - - -namespace py = boost::python; -using namespace karabo::util; - -namespace karathon { - static std::map> testServersRegistry; - - - static void _startDeviceServerPy(karabo::util::Hash& config) { - using namespace karabo::core; - if (!config.has("serverId")) config.set("serverId", "testDeviceServer"); - if (!config.has("Logger.priority")) config.set("Logger.priority", "FATAL"); - if (!config.has("scanPlugins")) config.set("scanPlugins", false); - auto deviceServer = DeviceServer::create("DeviceServer", config); - deviceServer->finalizeInternalInitialization(); - testServersRegistry[config.get("serverId")] = deviceServer; - } - - - static void _stopDeviceServerPy(const std::string& serverId) { - using namespace karabo::core; - auto it = testServersRegistry.find(serverId); - if (it == testServersRegistry.end()) return; - testServersRegistry.erase(it); - } - -} // namespace karathon - - -void exportPyKarathonTestUtilities() { - py::def("startDeviceServer", &karathon::_startDeviceServerPy, (py::arg("config"))); - py::def("stopDeviceServer", &karathon::_stopDeviceServerPy, (py::arg("serverId"))); -} diff --git a/src/karathon/p2pbinding.cc b/src/karathon/p2pbinding.cc deleted file mode 100644 index 77c0ce5357..0000000000 --- a/src/karathon/p2pbinding.cc +++ /dev/null @@ -1,207 +0,0 @@ -/* - * This file is part of Karabo. - * - * http://www.karabo.eu - * - * Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. - * - * Karabo is free software: you can redistribute it and/or modify it under - * the terms of the MPL-2 Mozilla Public License. - * - * You should have received a copy of the MPL-2 Public License along with - * Karabo. If not, see . - * - * Karabo is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. - */ - -#include -#include - -#include "ChannelWrap.hh" -#include "ConnectionWrap.hh" -#include "PythonFactoryMacros.hh" -#include "Wrapper.hh" -#include "karabo/net/Broker.hh" -#include "karabo/net/Connection.hh" -#include "karabo/net/EventLoop.hh" -#include "karabo/net/utils.hh" - -namespace bp = boost::python; - -using namespace std; -using namespace karabo::net; -using namespace karathon; - - -namespace karathon { - - static void EventLoopWorkWrap() { - ScopedGILRelease nogil; - EventLoop::work(); - } - - - static void EventLoopRunWrap() { - ScopedGILRelease nogil; - EventLoop::run(); - } - - static void EventLoopPostWrap(const bp::object& callable, const bp::object& delay) { - // Wrap with GIL since callable's reference count will increase: - HandlerWrap<> wrapped(callable, "EventLoop.post"); - unsigned int delayMillisec = 0; - if (delay.ptr() != Py_None) { - const double delaySeconds = bp::extract(delay); // needs GIL - delayMillisec = static_cast(delaySeconds * 1.e3); - } - // No GIL when entering pure C++: - ScopedGILRelease nogil; - EventLoop::post(std::move(wrapped), delayMillisec); - } - - static void EventLoopSetSignalHandler(const bp::object& handler) { - HandlerWrap wrapped(handler, "EventLoop.setSignalHandler"); - // No GIL when entering pure C++: - ScopedGILRelease nogil; - EventLoop::setSignalHandler(wrapped); - } - -} // namespace karathon - - -void exportp2p() { - bp::docstring_options docs(true, true, false); - - { - bp::enum_("ConnectionStatus") - .value("DISCONNECTED", ConnectionStatus::DISCONNECTED) - .value("CONNECTING", ConnectionStatus::CONNECTING) - .value("CONNECTED", ConnectionStatus::CONNECTED) - .value("DISCONNECTING", ConnectionStatus::DISCONNECTING); - } - - { - bp::class_("Broker", bp::no_init) - .def("expectedParameters", &Broker::expectedParameters, (bp::arg("schema"))) - .staticmethod("expectedParameters") - .def("getBrokerUrl", &Broker::getBrokerUrl, "Reports the url of the currently connected-to broker") - .def("brokerTypeFromEnv", &Broker::brokerTypeFromEnv) - .staticmethod("brokerTypeFromEnv") KARABO_PYTHON_FACTORY_CONFIGURATOR(Broker); - } - - { - bp::class_("ErrorCode", "This class keeps error condition: error code and error message.", - bp::init<>()) - .def("value", &ErrorCode::value, "Returns error code") - .def("message", (std::string(ErrorCode::*)() const) & ErrorCode::message, "Returns error message"); - } - - { - bp::class_("Connection", bp::no_init) - .def("start", &ConnectionWrap().start, - "Starts the connection synchronously, i.e. it blocks until connection " - "with remote peer is established. It returns a handle a.k.a channel used in all IO operations.") - .def("startAsync", &ConnectionWrap().startAsync, (bp::arg("handler")), - "Starts the connection asynchronously, i.e. it never blocks" - ", but if the connection is established, the provided handler will be called with the channel as " - "the argument to the handler.\nRegister " - "new handlers in this handler using given channel if you want follow asynchronous model.") - .def("stop", &ConnectionWrap().stop, "Stops IO service operation.") - KARABO_PYTHON_FACTORY_CONFIGURATOR(Connection); - } - - { - bp::class_( - "Channel", - "Channel is a class providing IO operations. The instance of this class can be created when connection " - "is established.", - bp::no_init) - - .def("getConnection", &Channel::getConnection, "Returns connection object for given channel") - .def("readStr", &ChannelWrap().readStr, - "Read message and return it as a python string. This function will block until message is arrived.") - .def("readHash", &ChannelWrap().readHash, - "Read message and return it as a Hash. This function will block until message is arrived.") - .def("readHashStr", &ChannelWrap().readHashStr, - "Read logical message that consists of two parts: header (Hash) & body (str). This function blocks " - "until all parts are arrived.") - .def("readHashHash", &ChannelWrap().readHashHash, - "Read logical message that consists of two parts: header (Hash) & body (Hash). This function " - "blocks until all parts are arrived.") - .def("readAsyncStr", &ChannelWrap().readAsyncStr, (bp::arg("handler")), - "Register handler that will be called when the message is arrived. Never blocks. The message will " - "be represented as bytearray.") - .def("readAsyncHash", &ChannelWrap().readAsyncHash, (bp::arg("handler")), - "Register handler that will be called when the next message arrives.\n" - "Never blocks, but requires running EventLoop.\n" - "Handler will be called with three arguments:\n" - " - an ErrorCode object\n" - " - the channel that called readAsyncHash\n" - " - the sent data deserialized to a Hash") - .def("readAsyncHashStr", &ChannelWrap().readAsyncHashStr, (bp::arg("handler")), - "Register handler that will be called when the message is arrived. Never blocks. The message will " - "have a header as Hash and a body as bytearray.") - .def("readAsyncHashHash", &ChannelWrap().readAsyncHashHash, (bp::arg("handler")), - "Register handler that will be called when the message is arrived. Never blocks. The message will " - "have a header and a body as two Hashes.") - .def("write", &ChannelWrap().write, (bp::arg("obj")), - "This method writes the object given in parameter list synchronously, i.e. blocks until the IO " - "operation is completed.") - .def("write", &ChannelWrap().write2, (bp::arg("obj"), bp::arg("body")), - "Helper method. It writes sequentially two messages: the header and the body. The operation is " - "synchronous, i.e. the method blocks " - "until the IO operation is completed.") - .def("writeAsyncStr", &ChannelWrap().writeAsyncStr, (bp::arg("data"), bp::arg("handler")), - "Register handler for write a string message. Never blocks. The handler will be called if write " - "operation is completed.") - .def("writeAsyncHash", &ChannelWrap().writeAsyncHash, (bp::arg("data"), bp::arg("handler")), - "Register handler for write a Hash message. Never blocks. The handler will be called if write " - "operation is completed.") - .def("writeAsyncHashStr", &ChannelWrap().writeAsyncHashStr, - (bp::arg("hdr"), bp::arg("data"), bp::arg("handler")), - "Helper method. Register handler for write a Hash header and 'string' body. Never blocks. The " - "handler will be called " - "if write operations of all message parts are completed.") - .def("writeAsyncHashHash", &ChannelWrap().writeAsyncHashHash, - (bp::arg("hdr"), bp::arg("data"), bp::arg("handler")), - "Helper method. Register handler for write a Hash header and Hash body. Never blocks. The handler " - "will be called " - "if write operations of all message parts are completed.") - .def("close", &Channel::close, "Close channel session.") - .add_property("__id__", &ChannelWrap().id, - "This readonly variable keeps id that uniquely identifies channel instance.") - KARABO_PYTHON_FACTORY_CONFIGURATOR(Channel); - } - - { - bp::class_( - "EventLoop", "EventLoop is a singleton class wrapping Boost ASIO functionality.", bp::no_init) - .def("work", &EventLoopWorkWrap, - "Start the event loop and block until EventLoop::stop() is called.\n\n" - "The system signals SIGINT and SIGTERM will be caught and trigger the\n" - "following actions:\n" - " - a signal handler set via setSignalHandler is called,\n" - " - and the event loop is stopped.") - .staticmethod("work") - .def("run", &EventLoopRunWrap) - .staticmethod("run") - .def("stop", &EventLoop::stop) - .staticmethod("stop") - .def("addThread", (void (*)(const int)) & EventLoop::addThread, (bp::arg("nThreads") = 1)) - .staticmethod("addThread") - .def("removeThread", (void (*)(const int)) & EventLoop::removeThread, (bp::arg("nThreads") = 1)) - .staticmethod("removeThread") - .def("getNumberOfThreads", (size_t(*)()) & EventLoop::getNumberOfThreads) - .staticmethod("getNumberOfThreads") - .def("post", &EventLoopPostWrap, (bp::arg("callable"), bp::arg("delay") = bp::object()), - "Post 'callable' for execution in background. Needs EventLoop to run/work.\n" - "If 'delay' is not None, execution is postponed by given seconds.") - .staticmethod("post") - .def("setSignalHandler", &EventLoopSetSignalHandler, (bp::arg("handler")), - "Set handler to be called if a system signal is caught in 'work',\n" - "'handler' has to take the signal value as argument.") - .staticmethod("setSignalHandler"); - } -} diff --git a/src/pythonKarabo/karabo/bound.py b/src/pythonKarabo/karabo/bound.py index 439b41e4a2..4278dd087d 100644 --- a/src/pythonKarabo/karabo/bound.py +++ b/src/pythonKarabo/karabo/bound.py @@ -17,6 +17,47 @@ """ This module provides all the bound API names which a Device might need. """ + +from karabind import ( + ADMIN, ALARM_ELEMENT, AMPERE, AMPERE_PER_SECOND, ATTO, ATTOSEC, BAR, BAYER, + BECQUEREL, BGR, BGRA, BIT, BMP, BOOL_ELEMENT, BYTE, BYTEARRAY_ELEMENT, + CANDELA, CENTI, CHOICE_ELEMENT, CHOICE_OF_NODES, CMYK, COMMAND, COULOMB, + COUNT, DAY, DECA, DECI, DEGREE, DEGREE_CELSIUS, DOUBLE_ELEMENT, + ELECTRONVOLT, EVERY_1MIN, EVERY_1S, EVERY_5S, EVERY_10MIN, EVERY_10S, + EVERY_100MS, EVERY_EVENT, EXA, EXPERT, FARAD, FEMTO, FEMTOSEC, + FLOAT_ELEMENT, GIGA, GRAM, GRAY, HECTO, HENRY, HERTZ, HOUR, + IMAGEDATA_ELEMENT, INIT, INPUT_CHANNEL, INPUT_ELEMENT, INT32_ELEMENT, + INT64_ELEMENT, INTERNAL, JOULE, JPEG, KATAL, KELVIN, KILO, LEAF, + LIST_ELEMENT, LIST_OF_NODES, LUMEN, LUX, MANDATORY, MEGA, METER, + METER_PER_SECOND, MICRO, MICROSEC, MILLI, MILLISEC, MINUTE, MOLE, NANO, + NANOSEC, NDARRAY_ELEMENT, NEWTON, NO_ARCHIVING, NODE, NODE_ELEMENT, NONE, + NOT_ASSIGNED, NUMBER, OBSERVER, OHM, ONESECOND, OPERATOR, OPTIONAL, + OUTPUT_CHANNEL, OUTPUT_ELEMENT, OVERWRITE_ELEMENT, PASCAL, PATH_ELEMENT, + PERCENT, PETA, PICO, PICOSEC, PIXEL, PNG, PROPERTY, RADIAN, READ, RGB, + RGBA, SECOND, SIEMENS, SIEVERT, SLOT_ELEMENT, STATE_ELEMENT, STERADIAN, + STRING_ELEMENT, TABLE_ELEMENT, TERA, TESLA, TIFF, TIME_UNITS, + UINT32_ELEMENT, UINT64_ELEMENT, UNDEFINED, USER, VECTOR_BOOL_ELEMENT, + VECTOR_CHAR_ELEMENT, VECTOR_DOUBLE_ELEMENT, VECTOR_FLOAT_ELEMENT, + VECTOR_INT32_ELEMENT, VECTOR_INT64_ELEMENT, VECTOR_STRING, + VECTOR_STRING_ELEMENT, VECTOR_UINT32_ELEMENT, VECTOR_UINT64_ELEMENT, VOLT, + VOLT_PER_SECOND, WATT, WEBER, WRITE, YEAR, YOCTO, YOTTA, YUV, ZEPTO, ZETTA, + AccessLevel, AccessType, ArchivePolicy, AssemblyRules, AssignmentType, + BinarySerializerHash, BinarySerializerSchema, Broker, Category, Channel, + ChannelMetaData, ClassInfo, Connection, ConnectionStatus, DaqDataType, + DAQPolicy, DateTimeString, DeviceClient as BoundDeviceClient, Dims, + Encoding, Epochstamp, ErrorCode, EventLoop, Hash, HashAttributes, + HashAttributesNode, HashFilter, HashMergePolicy, HashNode, ImageData, + InputChannel, InputHash, InputSchema, LeafType, Logger, MetricPrefix, + NodeType, OutputChannel, OutputHash, OutputSchema, Priority, PriorityLevel, + Requestor, RollingWindowStatistics, Rotation, Schema, SignalSlotable, + SignalSlotableIntern, Slot, SlotElementBase, TextSerializerHash, + TextSerializerSchema, TimeDuration, Timestamp, Trainstamp, Types, + TypesClass, Unit, Validator, ValidatorValidationRules, VectorHash, + VectorHashPointer, _DimsIntern, cppNDArray, cppNDArrayCopy, fullyEqual, + generateAutoStartHash, jsonToHash, loadFromFile, loadHashFromFile, + loadSchemaFromFile, saveHashToFile, saveSchemaToFile, saveToFile, setDims, + similar, startDeviceServer, stopDeviceServer) + from .bound_api.base_fsm import BaseFsm from .bound_api.camera_fsm import CameraFsm from .bound_api.configurator import Configurator @@ -47,44 +88,27 @@ from .bound_api.start_stop_fsm import StartStopFsm from .bound_api.start_stop_fsm_periodic import StartStopFsmPeriodic from .bound_api.worker import QueueWorker, Worker -from .bound_tool import ( - ADMIN, ALARM_ELEMENT, AMPERE, AMPERE_PER_SECOND, ATTO, ATTOSEC, BAR, BAYER, - BECQUEREL, BGR, BGRA, BIT, BMP, BOOL_ELEMENT, BYTE, BYTEARRAY_ELEMENT, - CANDELA, CENTI, CHOICE_ELEMENT, CHOICE_OF_NODES, CMYK, COMMAND, COULOMB, - COUNT, DAY, DECA, DECI, DEGREE, DEGREE_CELSIUS, DOUBLE_ELEMENT, - ELECTRONVOLT, EVERY_1MIN, EVERY_1S, EVERY_5S, EVERY_10MIN, EVERY_10S, - EVERY_100MS, EVERY_EVENT, EXA, EXPERT, FARAD, FEMTO, FEMTOSEC, - FLOAT_ELEMENT, GIGA, GRAM, GRAY, HECTO, HENRY, HERTZ, HOUR, - IMAGEDATA_ELEMENT, INIT, INPUT_CHANNEL, INPUT_ELEMENT, INT32_ELEMENT, - INT64_ELEMENT, INTERNAL, JOULE, JPEG, KATAL, KELVIN, KILO, LEAF, - LIST_ELEMENT, LIST_OF_NODES, LUMEN, LUX, MANDATORY, MEGA, METER, - METER_PER_SECOND, MICRO, MICROSEC, MILLI, MILLISEC, MINUTE, MOLE, NANO, - NANOSEC, NDARRAY_ELEMENT, NEWTON, NO_ARCHIVING, NODE, NODE_ELEMENT, NONE, - NOT_ASSIGNED, NUMBER, OBSERVER, OHM, ONESECOND, OPERATOR, OPTIONAL, - OUTPUT_CHANNEL, OUTPUT_ELEMENT, OVERWRITE_ELEMENT, PASCAL, PATH_ELEMENT, - PERCENT, PETA, PICO, PICOSEC, PIXEL, PNG, PROPERTY, RADIAN, READ, RGB, - RGBA, SECOND, SIEMENS, SIEVERT, SLOT_ELEMENT, STATE_ELEMENT, STERADIAN, - STRING_ELEMENT, TABLE_ELEMENT, TERA, TESLA, TIFF, TIME_UNITS, - UINT32_ELEMENT, UINT64_ELEMENT, UNDEFINED, USER, VECTOR_BOOL_ELEMENT, - VECTOR_CHAR_ELEMENT, VECTOR_DOUBLE_ELEMENT, VECTOR_FLOAT_ELEMENT, - VECTOR_INT32_ELEMENT, VECTOR_INT64_ELEMENT, VECTOR_STRING_ELEMENT, - VECTOR_UINT32_ELEMENT, VECTOR_UINT64_ELEMENT, VOLT, VOLT_PER_SECOND, WATT, - WEBER, WRITE, YEAR, YOCTO, YOTTA, YUV, ZEPTO, ZETTA, AbstractInput, - AccessLevel, AccessType, ArchivePolicy, AssemblyRules, AssignmentType, - BinarySerializerHash, BinarySerializerSchema, Broker, Category, Channel, - ChannelMetaData, ClassInfo, Connection, ConnectionStatus, DaqDataType, - DAQPolicy, DateTimeString, Dims, Encoding, Epochstamp, ErrorCode, - EventLoop, Hash, HashAttributes, HashAttributesNode, HashFilter, - HashMergePolicy, HashNode, ImageData, InputChannel, InputHash, InputSchema, - LeafType, Logger, MetricPrefix, NodeType, OutputChannel, OutputHash, - OutputSchema, Priority, PriorityLevel, Requestor, RollingWindowStatistics, - Rotation, Schema, SignalSlotable, SignalSlotableIntern, Slot, - SlotElementBase, TextSerializerHash, TextSerializerSchema, TimeDuration, - Timestamp, Trainstamp, Types, TypesClass, Unit, Validator, - ValidatorValidationRules, VectorHash, VectorHashPointer, _DimsIntern, - fullyEqual, isStdVectorDefaultConversion, loadFromFile, loadHashFromFile, - loadSchemaFromFile, saveHashToFile, saveSchemaToFile, saveToFile, setDims, - setStdVectorDefaultConversion, similar, startDeviceServer, - stopDeviceServer) from .common.alarm_conditions import AlarmCondition +# For comptibility with old karathon bindings, take care that e.g. +# str(Types.INT32) is 'INT32' and not 'Types.INT32' from .common.states import State, StateSignifier + + +def __typesToString(self): + repStr = repr(self) # i.e. '' + return repStr[7:repStr.find(':')] + + +setattr(Types, "__str__", __typesToString) + + +class AbstractInput: + pass + + +def isStdVectorDefaultConversion(): + return True + + +def setStdVectorDefaultConversion(): + pass diff --git a/src/pythonKarabo/karabo/bound_api/camera_fsm.py b/src/pythonKarabo/karabo/bound_api/camera_fsm.py index d98704e71f..434667850f 100644 --- a/src/pythonKarabo/karabo/bound_api/camera_fsm.py +++ b/src/pythonKarabo/karabo/bound_api/camera_fsm.py @@ -17,7 +17,7 @@ __date__ = "August 7, 2013" import karabo.bound_api.base_fsm as base -from karabo.bound_tool import SLOT_ELEMENT, VECTOR_STRING_ELEMENT +from karabind import SLOT_ELEMENT, VECTOR_STRING_ELEMENT from karabo.common.states import State from .decorators import KARABO_CLASSINFO diff --git a/src/pythonKarabo/karabo/bound_api/configurator.py b/src/pythonKarabo/karabo/bound_api/configurator.py index f02a0d0f68..7a2187eb54 100644 --- a/src/pythonKarabo/karabo/bound_api/configurator.py +++ b/src/pythonKarabo/karabo/bound_api/configurator.py @@ -16,7 +16,7 @@ # To change this template, choose Tools | Templates # and open the template in the editor. -from karabo.bound_tool import AssemblyRules, Schema, Validator +from karabind import AssemblyRules, Schema, Validator class Configurator: diff --git a/src/pythonKarabo/karabo/bound_api/device.py b/src/pythonKarabo/karabo/bound_api/device.py index 69c1d233c9..deea443757 100644 --- a/src/pythonKarabo/karabo/bound_api/device.py +++ b/src/pythonKarabo/karabo/bound_api/device.py @@ -22,8 +22,7 @@ import threading import time -from karabo import __version__ as karaboVersion -from karabo.bound_tool import ( +from karabind import ( ALARM_ELEMENT, BOOL_ELEMENT, FLOAT_ELEMENT, INT32_ELEMENT, MICROSEC, NODE_ELEMENT, OBSERVER, OVERWRITE_ELEMENT, SLOT_ELEMENT, STATE_ELEMENT, STRING_ELEMENT, UINT32_ELEMENT, WRITE, AccessLevel, AccessType, @@ -31,6 +30,7 @@ EventLoop, Hash, HashFilter, HashMergePolicy, LeafType, Logger, MetricPrefix, Schema, SignalSlotable, Timestamp, Trainstamp, Unit, Validator, ValidatorValidationRules, VectorHash, loadFromFile) +from karabo import __version__ as karaboVersion from karabo.common.api import ( KARABO_LOGGER_CONTENT_DEFAULT, AlarmCondition, Capabilities, Interfaces, State, karabo_deprecated) diff --git a/src/pythonKarabo/karabo/bound_api/device_client.py b/src/pythonKarabo/karabo/bound_api/device_client.py index 074c766058..3e692a1e9a 100644 --- a/src/pythonKarabo/karabo/bound_api/device_client.py +++ b/src/pythonKarabo/karabo/bound_api/device_client.py @@ -14,7 +14,7 @@ # WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. -from karabo.bound_tool import BoundDeviceClient, Hash, LeafType +from karabind import DeviceClient as BoundDeviceClient, Hash, LeafType from karabo.common.alarm_conditions import AlarmCondition from karabo.common.states import State diff --git a/src/pythonKarabo/karabo/bound_api/device_server.py b/src/pythonKarabo/karabo/bound_api/device_server.py index 7429233ef4..729f61559b 100644 --- a/src/pythonKarabo/karabo/bound_api/device_server.py +++ b/src/pythonKarabo/karabo/bound_api/device_server.py @@ -30,7 +30,7 @@ from itertools import chain from subprocess import Popen, TimeoutExpired -from karabo.bound_tool import ( +from karabind import ( CHOICE_ELEMENT, INT32_ELEMENT, LIST_ELEMENT, NODE_ELEMENT, OVERWRITE_ELEMENT, STRING_ELEMENT, VECTOR_STRING_ELEMENT, AccessLevel, Broker, EventLoop, Hash, Logger, Schema, SignalSlotable, Unit, Validator, diff --git a/src/pythonKarabo/karabo/bound_api/ok_error_fsm.py b/src/pythonKarabo/karabo/bound_api/ok_error_fsm.py index 48288e4106..4ede8b861c 100644 --- a/src/pythonKarabo/karabo/bound_api/ok_error_fsm.py +++ b/src/pythonKarabo/karabo/bound_api/ok_error_fsm.py @@ -20,7 +20,7 @@ __date__ = "$May 12, 2013 5:09:05 PM$" import karabo.bound_api.base_fsm as base -from karabo.bound_tool import SLOT_ELEMENT +from karabind import SLOT_ELEMENT from karabo.common.states import State from .decorators import KARABO_CLASSINFO diff --git a/src/pythonKarabo/karabo/bound_api/plugin_loader.py b/src/pythonKarabo/karabo/bound_api/plugin_loader.py index 8aceb5208a..9b084c34f1 100644 --- a/src/pythonKarabo/karabo/bound_api/plugin_loader.py +++ b/src/pythonKarabo/karabo/bound_api/plugin_loader.py @@ -17,7 +17,7 @@ from pkg_resources import WorkingSet -from karabo.bound_tool import STRING_ELEMENT +from karabind import STRING_ELEMENT from .decorators import KARABO_CLASSINFO, KARABO_CONFIGURATION_BASE_CLASS diff --git a/src/pythonKarabo/karabo/bound_api/runner.py b/src/pythonKarabo/karabo/bound_api/runner.py index a809926149..f83d047887 100644 --- a/src/pythonKarabo/karabo/bound_api/runner.py +++ b/src/pythonKarabo/karabo/bound_api/runner.py @@ -20,8 +20,7 @@ import os import re -from karabo.bound_tool import ( - Hash, generateAutoStartHash, jsonToHash, loadFromFile) +from karabind import Hash, generateAutoStartHash, jsonToHash, loadFromFile from .decorators import KARABO_CLASSINFO, KARABO_CONFIGURATION_BASE_CLASS diff --git a/src/pythonKarabo/karabo/bound_api/start_stop_fsm.py b/src/pythonKarabo/karabo/bound_api/start_stop_fsm.py index 4a132dbdaa..e0ac9357d7 100644 --- a/src/pythonKarabo/karabo/bound_api/start_stop_fsm.py +++ b/src/pythonKarabo/karabo/bound_api/start_stop_fsm.py @@ -20,7 +20,7 @@ __date__ = "$May 10, 2013 2:35:08 PM$" import karabo.bound_api.base_fsm as base -from karabo.bound_tool import SLOT_ELEMENT +from karabind import SLOT_ELEMENT from karabo.common.states import State from .decorators import KARABO_CLASSINFO diff --git a/src/pythonKarabo/karabo/bound_api/start_stop_fsm_periodic.py b/src/pythonKarabo/karabo/bound_api/start_stop_fsm_periodic.py index 0b8698ae59..e0ae9169de 100644 --- a/src/pythonKarabo/karabo/bound_api/start_stop_fsm_periodic.py +++ b/src/pythonKarabo/karabo/bound_api/start_stop_fsm_periodic.py @@ -17,7 +17,7 @@ __date__ = "$May 10, 2013 2:35:08 PM$" import karabo.bound_api.base_fsm as base -from karabo.bound_tool import SLOT_ELEMENT +from karabind import SLOT_ELEMENT from karabo.common.states import State from .decorators import KARABO_CLASSINFO diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_attributes.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_attributes.py index b1e7bedc1c..468a54b908 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_attributes.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_attributes.py @@ -17,7 +17,6 @@ from karabo.bound import ( HashAttributes as Attributes, HashAttributesNode as Node, Types) -from karabo.bound_tool import use_karathon def test_constructor(): @@ -31,12 +30,8 @@ def test_constructor(): # Construction of HashAttributesNode is not possible in python # (but exceptions differ) - if not use_karathon: - with pytest.raises(TypeError): - _ = Node() - else: - with pytest.raises(RuntimeError): - _ = Node() + with pytest.raises(TypeError): + _ = Node() def test_set(): @@ -102,15 +97,14 @@ def test_set(): ha['attr16'] = [1.11111, 2.222222, 3.333333] assert ha.getNode('attr16').getType() == Types.VECTOR_DOUBLE # VECTOR_COMPLEX_DOUBLE - if not use_karathon: - ha['attr17'] = [complex(1.0, -5), complex(-2., 188)] - assert ha.getNode('attr17').getType() == Types.VECTOR_COMPLEX_DOUBLE - assert ha.getType('attr17') == Types.VECTOR_COMPLEX_DOUBLE - assert ha.isType('attr17', Types.VECTOR_COMPLEX_DOUBLE) - assert ha.isType('attr17', "VECTOR_COMPLEX_DOUBLE") - ha.erase('attr17') - ha['attr17'] = [complex(1.0, -5), complex(-2., 188)] - del ha['attr17'] + ha['attr17'] = [complex(1.0, -5), complex(-2., 188)] + assert ha.getNode('attr17').getType() == Types.VECTOR_COMPLEX_DOUBLE + assert ha.getType('attr17') == Types.VECTOR_COMPLEX_DOUBLE + assert ha.isType('attr17', Types.VECTOR_COMPLEX_DOUBLE) + assert ha.isType('attr17', "VECTOR_COMPLEX_DOUBLE") + ha.erase('attr17') + ha['attr17'] = [complex(1.0, -5), complex(-2., 188)] + del ha['attr17'] # VECTOR_STRING ha['attr18'] = ['aaaa', 'bbb', 'cccccccc', 'www'] @@ -125,56 +119,40 @@ def test_set(): assert node6.getKey() == 'attr6' assert node6.getType() == Types.STRING assert node6.getValue() == 'abrakadabra' - # Implemented only in karabind: check attribute type - if not use_karathon: - assert ha.getType('attr1') == Types.BOOL - assert ha.isType('attr1', Types.BOOL) - assert ha.isType('attr1', "BOOL") - assert ha.getType('attr2') == Types.INT32 - assert ha.isType('attr2', Types.INT32) - assert ha.isType('attr2', "INT32") - assert ha.getType('attr3') == Types.INT64 - assert ha.isType('attr3', Types.INT64) - assert ha.isType('attr3', "INT64") - assert ha.getType('attr4') == Types.DOUBLE - assert ha.isType('attr4', Types.DOUBLE) - assert ha.isType('attr4', "DOUBLE") - assert ha.getType('attr5') == Types.COMPLEX_DOUBLE - assert ha.isType('attr5', Types.COMPLEX_DOUBLE) - assert ha.isType('attr5', "COMPLEX_DOUBLE") - assert ha.getType('attr6') == Types.STRING - assert ha.isType('attr6', Types.STRING) - assert ha.isType('attr6', "STRING") - assert ha.getType('attr13') == Types.VECTOR_BOOL - assert ha.isType('attr13', Types.VECTOR_BOOL) - assert ha.isType('attr13', "VECTOR_BOOL") - assert ha.getType('attr14') == Types.VECTOR_INT32 - assert ha.isType('attr14', Types.VECTOR_INT32) - assert ha.isType('attr14', "VECTOR_INT32") - assert ha.getType('attr15') == Types.VECTOR_INT64 - assert ha.isType('attr15', Types.VECTOR_INT64) - assert ha.isType('attr15', "VECTOR_INT64") - assert ha.getType('attr16') == Types.VECTOR_DOUBLE - assert ha.isType('attr16', Types.VECTOR_DOUBLE) - assert ha.isType('attr16', "VECTOR_DOUBLE") - assert ha.getType('attr18') == Types.VECTOR_STRING - assert ha.isType('attr18', Types.VECTOR_STRING) - assert ha.isType('attr18', "VECTOR_STRING") - assert not ha.isType('attr15', "INT64") - - if use_karathon: - assert ha.getNode('attr1').getType() == Types.BOOL - assert ha.getNode('attr2').getType() == Types.INT32 - assert ha.getNode('attr3').getType() == Types.INT64 - assert ha.getNode('attr4').getType() == Types.DOUBLE - assert ha.getNode('attr5').getType() == Types.COMPLEX_DOUBLE - assert ha.getNode('attr6').getType() == Types.STRING - - assert ha.getNode('attr13').getType() == Types.VECTOR_BOOL - assert ha.getNode('attr14').getType() == Types.VECTOR_INT32 - assert ha.getNode('attr15').getType() == Types.VECTOR_INT64 - assert ha.getNode('attr16').getType() == Types.VECTOR_DOUBLE - assert ha.getNode('attr18').getType() == Types.VECTOR_STRING + assert ha.getType('attr1') == Types.BOOL + assert ha.isType('attr1', Types.BOOL) + assert ha.isType('attr1', "BOOL") + assert ha.getType('attr2') == Types.INT32 + assert ha.isType('attr2', Types.INT32) + assert ha.isType('attr2', "INT32") + assert ha.getType('attr3') == Types.INT64 + assert ha.isType('attr3', Types.INT64) + assert ha.isType('attr3', "INT64") + assert ha.getType('attr4') == Types.DOUBLE + assert ha.isType('attr4', Types.DOUBLE) + assert ha.isType('attr4', "DOUBLE") + assert ha.getType('attr5') == Types.COMPLEX_DOUBLE + assert ha.isType('attr5', Types.COMPLEX_DOUBLE) + assert ha.isType('attr5', "COMPLEX_DOUBLE") + assert ha.getType('attr6') == Types.STRING + assert ha.isType('attr6', Types.STRING) + assert ha.isType('attr6', "STRING") + assert ha.getType('attr13') == Types.VECTOR_BOOL + assert ha.isType('attr13', Types.VECTOR_BOOL) + assert ha.isType('attr13', "VECTOR_BOOL") + assert ha.getType('attr14') == Types.VECTOR_INT32 + assert ha.isType('attr14', Types.VECTOR_INT32) + assert ha.isType('attr14', "VECTOR_INT32") + assert ha.getType('attr15') == Types.VECTOR_INT64 + assert ha.isType('attr15', Types.VECTOR_INT64) + assert ha.isType('attr15', "VECTOR_INT64") + assert ha.getType('attr16') == Types.VECTOR_DOUBLE + assert ha.isType('attr16', Types.VECTOR_DOUBLE) + assert ha.isType('attr16', "VECTOR_DOUBLE") + assert ha.getType('attr18') == Types.VECTOR_STRING + assert ha.isType('attr18', Types.VECTOR_STRING) + assert ha.isType('attr18', "VECTOR_STRING") + assert not ha.isType('attr15', "INT64") ha.clear() assert (ha.empty()) @@ -219,10 +197,7 @@ def test_changetype(): ha['a'] = 65 def current_type_is(reftype): - if not use_karathon: - assert ha.getType('a') == reftype - if use_karathon: - assert ha.getNode('a').getType() == reftype + assert ha.getType('a') == reftype current_type_is(Types.INT32) # Get as INT64 @@ -237,8 +212,7 @@ def current_type_is(reftype): with pytest.raises(RuntimeError): assert (ha.getAs('a', "BOOL")) # Get as COMPLEX_DOUBLE - if not use_karathon: - assert ha.getAs('a', "COMPLEX_DOUBLE") == complex(65, 0) + assert ha.getAs('a', "COMPLEX_DOUBLE") == complex(65, 0) # Get as STRING assert ha.getAs('a', "STRING") == '65' diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash.py index bf9844fdfe..577de6b756 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash.py @@ -21,7 +21,6 @@ from karabo.bound import ( Hash, HashMergePolicy, HashNode as Node, Types, VectorHash, fullyEqual, similar) -from karabo.bound_tool import use_karathon # Test "clear", "empty", "getKeys", "keys", "getValues", "values", # "getPaths", "paths", "set", "__setitem__", "setAs", "get", @@ -63,9 +62,8 @@ def test_constructor(): with pytest.raises(TypeError): h = Hash('a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 'g', 7) # Cannot construct Node object in Python ... - if not use_karathon: - with pytest.raises(TypeError): - print(Node()) + with pytest.raises(TypeError): + print(Node()) def test_getset(): @@ -98,9 +96,8 @@ def test_getset(): # Test "isType" assert h.isType('a', Types.STRING) assert h.isType('c.c.c.c', Types.BOOL) - if not use_karathon: - assert h.isType('a', "STRING") - assert h.isType('c.c.c.c', "BOOL") + assert h.isType('a', "STRING") + assert h.isType('c.c.c.c', "BOOL") # Test "has" assert h.has('p.e.r.f') @@ -272,12 +269,10 @@ def test_getset(): assert h['a.b.c.d.e.f'] == 88 # drop the parent Hash in Python del h - # attempt to access 'g' or 't' gives crash!!! - # Now only in karathon! karabind is fixed using lifetime - # control via 'keep_alive<...>()' magic - if not use_karathon: - assert g['d.e.f'], 88 - assert t['f'], 88 + # Attempt to access 'g' or 't' gives possible despite 'h' is gone + # (lifetime extended via 'keep_alive<...>()' magic) + assert g['d.e.f'] == 88 + assert t['f'] == 88 h = Hash("a[0]", Hash("a", 1), "a[1]", Hash("a", 1)) assert h["a[0].a"] == 1, "Value should be 1" @@ -370,29 +365,21 @@ def test_getsetVectorHash(): def test_copy_and_VectorHash(): arr = np.arange(20000, dtype=np.int16).reshape(100, 200) assert arr[0][0] == 0 - if not use_karathon: - v = VectorHash([Hash('a', arr), Hash('b', 2)]) - else: - # karathon supports only default constructor - v = VectorHash() - v.append(Hash('a', arr)) - v.append(Hash('b', 2)) + v = VectorHash([Hash('a', arr), Hash('b', 2)]) + # Shallow copy ... vc = copy.copy(v) assert not id(vc) == id(v) - # karathon has no deepcopy - if not use_karathon: - # Deep copy ... - vd = copy.deepcopy(v) - assert not id(vd) == id(v) + + vd = copy.deepcopy(v) + assert not id(vd) == id(v) # Change origin vector... arr[0][0] = 111 assert v[0]['a'][0][0] == 111 # Shallow copy has seen the change ... assert vc[0]['a'][0][0] == 111 - if not use_karathon: - # But deep copy is unchanged ... - assert vd[0]['a'][0][0] == 0 + # But deep copy is unchanged ... + assert vd[0]['a'][0][0] == 0 def test_getAs(): @@ -416,9 +403,8 @@ def test_getAs(): assert h.getAs("a", Types.UINT64) == 1 assert h.getAs("a", Types.FLOAT) == 1.0 assert h.getAs("a", Types.DOUBLE) == 1.0 - if not use_karathon: - assert h.getAs("a", Types.COMPLEX_FLOAT) == (1 + 0j) - assert h.getAs("a", Types.COMPLEX_DOUBLE) == (1 + 0j) + assert h.getAs("a", Types.COMPLEX_FLOAT) == (1 + 0j) + assert h.getAs("a", Types.COMPLEX_DOUBLE) == (1 + 0j) assert h.getAs("a", Types.STRING) == "1" assert h.getAs("a", Types.VECTOR_BOOL) == [True] @@ -433,8 +419,7 @@ def test_getAs(): assert h.getAs("a", Types.VECTOR_DOUBLE) == [1.0] assert h.getAs("a", Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] assert h.getAs("a", Types.VECTOR_COMPLEX_DOUBLE) == [(1 + 0j)] - if not use_karathon: - assert h.getAs("a", Types.VECTOR_STRING) == ['1'] + assert h.getAs("a", Types.VECTOR_STRING) == ['1'] def test_getAttributeAs(): @@ -452,14 +437,12 @@ def test_getAttributeAs(): assert h.getAttributeAs("a", "a", Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] assert h.getAttributeAs("a", "a", Types.VECTOR_COMPLEX_DOUBLE) == [ (1 + 0j)] - if not use_karathon: - assert h.getAttributeAs("a", "a", Types.VECTOR_STRING), ['1'] + assert h.getAttributeAs("a", "a", Types.VECTOR_STRING), ['1'] # DOUBLE h.setAttribute("a", "c", 1.23) assert h.getAttributes("a").getNode('c').getType() == Types.DOUBLE - if not use_karathon: - assert h.getAttributeType('a', 'c') == Types.DOUBLE + assert h.getAttributeType('a', 'c') == Types.DOUBLE h = Hash('a', 1) # Check that `getAttributes(...)` return reference internal @@ -504,10 +487,7 @@ def test_setAs(): h.setAs("a", [127, 0, 77], Types.VECTOR_INT8) assert h.getType("a") == Types.VECTOR_INT8 # byte array: 0x7f -> 127, 0x00 -> 0, 'M' -> 77 - if use_karathon: - assert h["a"] == bytearray(b'\x7f\x00M') - elif not use_karathon: - assert h["a"] == [127, 0, 77] + assert h["a"] == [127, 0, 77] h.setAs("a", [1260, -21170, 0, 1], Types.VECTOR_INT16) assert h.getType("a") == Types.VECTOR_INT16 @@ -517,14 +497,13 @@ def test_setAs(): assert h.getType("a") == Types.VECTOR_DOUBLE assert h["a"] == [1260.0, -21170.0, 0.0, 1.0] - if not use_karathon: - h.setAs("a", [1260, -21170, 0, 1], Types.VECTOR_COMPLEX_FLOAT) - assert h.getType("a") == Types.VECTOR_COMPLEX_FLOAT - assert h["a"] == [(1260 + 0j), (-21170 + 0j), 0j, (1 + 0j)] + h.setAs("a", [1260, -21170, 0, 1], Types.VECTOR_COMPLEX_FLOAT) + assert h.getType("a") == Types.VECTOR_COMPLEX_FLOAT + assert h["a"] == [(1260 + 0j), (-21170 + 0j), 0j, (1 + 0j)] - h.setAs("a", [1260, -21170, 0, 1], Types.VECTOR_STRING) - assert h.getType("a") == Types.VECTOR_STRING - assert h["a"] == ['1260', '-21170', '0', '1'] + h.setAs("a", [1260, -21170, 0, 1], Types.VECTOR_STRING) + assert h.getType("a") == Types.VECTOR_STRING + assert h["a"] == ['1260', '-21170', '0', '1'] def test_merge(): @@ -962,15 +941,14 @@ def test_ndarray(): assert h2['a'][0][0] == 255 assert arr[0][0] == 255 - if not use_karathon: - # Check 'deepcopy': it copies even underlying NDArray - g = copy.deepcopy(h) - assert g['a'][0][0] == 255 + # Check 'deepcopy': it copies even underlying NDArray + g = copy.deepcopy(h) + assert g['a'][0][0] == 255 - h['a'][0][0] = 1 + h['a'][0][0] = 1 - assert h['a'][0][0] == 1 - assert g['a'][0][0] == 255 + assert h['a'][0][0] == 1 + assert g['a'][0][0] == 255 # Check fortran order array: # Since the C++ NDArray only knows C order, it has to be copied diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes.py index 918e5f57d8..50722c67cd 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes.py @@ -17,7 +17,6 @@ import pytest from karabo.bound import Hash, HashAttributes, HashAttributesNode, Types -from karabo.bound_tool import use_karathon def test_hashAttributes(): @@ -67,10 +66,9 @@ def test_hashAttributes(): assert attrs["minerale"] == [True, False] # Test "getType", "isType" - if not use_karathon: - # check attribute types ... - assert attrs.getType('minerale') == Types.VECTOR_BOOL - # assert attrs.isType('minerale', "VECTOR_BOOL") is True + # check attribute types ... + assert attrs.getType('minerale') == Types.VECTOR_BOOL + # assert attrs.isType('minerale', "VECTOR_BOOL") is True # Test "__contains__ ..." assert "aq" in attrs @@ -151,9 +149,8 @@ def test_hashAttributes(): assert attrs.getAs("a2", Types.VECTOR_BOOL) == [True] assert attrs.getAs("a2", "VECTOR_UINT64") == [1] assert attrs.getAs("a2", "FLOAT") == 1.0 - if not use_karathon: - assert attrs.getAs("a2", "COMPLEX_FLOAT") == (1+0j) - assert attrs.getAs("a2", "VECTOR_COMPLEX_DOUBLE") == [(1+0j)] + assert attrs.getAs("a2", "COMPLEX_FLOAT") == (1+0j) + assert attrs.getAs("a2", "VECTOR_COMPLEX_DOUBLE") == [(1+0j)] assert attrs.getAs("a1", Types.UINT32) == 12 assert attrs.getAs("a1", "STRING") == '12' diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes_node.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes_node.py index 0f8a171615..984d9478a3 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes_node.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_attributes_node.py @@ -15,7 +15,6 @@ # FITNESS FOR A PARTICULAR PURPOSE. from karabo.bound import Hash, HashAttributes, HashAttributesNode, Types -from karabo.bound_tool import use_karathon def test_hashAttributesNode_getValueAs(): @@ -54,9 +53,8 @@ def test_hashAttributesNode_getValueAs(): assert n1.getValueAs(Types.UINT64) == 10 assert n1.getValueAs(Types.FLOAT) == 10 assert n1.getValueAs(Types.DOUBLE) == 10 - if not use_karathon: - assert n1.getValueAs(Types.COMPLEX_FLOAT) == (10+0j) - assert n1.getValueAs(Types.COMPLEX_DOUBLE) == (10+0j) + assert n1.getValueAs(Types.COMPLEX_FLOAT) == (10+0j) + assert n1.getValueAs(Types.COMPLEX_DOUBLE) == (10+0j) assert n1.getValueAs(Types.STRING) == '10' assert n1.getValueAs("STRING") == '10' assert ( @@ -67,12 +65,11 @@ def test_hashAttributesNode_getValueAs(): assert n2.getValueAs("VECTOR_UINT32") == [1, 0] assert n2.getValueAs("VECTOR_INT64") == [1, 0] assert n2.getValueAs("VECTOR_UINT64") == [1, 0] - if not use_karathon: - assert n2.getValueAs("VECTOR_FLOAT") == [1.0, 0.0] - assert n2.getValueAs("VECTOR_DOUBLE") == [1.0, 0.0] - assert n2.getValueAs("VECTOR_COMPLEX_FLOAT") == [(1+0j), (0+0j)] - assert n2.getValueAs("VECTOR_COMPLEX_DOUBLE") == [(1+0j), (0+0j)] - assert n2.getValueAs("VECTOR_STRING") == ['1', '0'] + assert n2.getValueAs("VECTOR_FLOAT") == [1.0, 0.0] + assert n2.getValueAs("VECTOR_DOUBLE") == [1.0, 0.0] + assert n2.getValueAs("VECTOR_COMPLEX_FLOAT") == [(1+0j), (0+0j)] + assert n2.getValueAs("VECTOR_COMPLEX_DOUBLE") == [(1+0j), (0+0j)] + assert n2.getValueAs("VECTOR_STRING") == ['1', '0'] # Test 'setType' & 'setValue' for INT8 h.setAttribute("a.b.c", "attr1", 10) @@ -301,26 +298,25 @@ def test_hashAttributesNode_getValueAs(): n1.setValue([111.22222, 33333.4444]) assert n1.getValue() == [111.22222, 33333.4444] - if not use_karathon: - # 'setType' VECTOR_COMPLEX_FLOAT - h.setAttribute("a.b.c", "attr1", 10) - attrs = h.getAttributes("a.b.c") - n1 = attrs.getNode("attr1") - n1.setType("VECTOR_COMPLEX_FLOAT") - assert n1.getType() == Types.VECTOR_COMPLEX_FLOAT - assert n1.getValue() == [(10+0j)] - n1.setValue([(1.2-3.2j), (5.4+3.3j)]) - assert n1.getValue() == [(1.2-3.2j), (5.4+3.3j)] - - # 'setType' VECTOR_COMPLEX_DOUBLE - h.setAttribute("a.b.c", "attr1", 10) - attrs = h.getAttributes("a.b.c") - n1 = attrs.getNode("attr1") - n1.setType("VECTOR_COMPLEX_DOUBLE") - assert n1.getType() == Types.VECTOR_COMPLEX_DOUBLE - assert n1.getValue() == [(10+0j)] - n1.setValue([(1.2-3.2j), (5.4+3.3j)]) - assert n1.getValue() == [(1.2-3.2j), (5.4+3.3j)] + # 'setType' VECTOR_COMPLEX_FLOAT + h.setAttribute("a.b.c", "attr1", 10) + attrs = h.getAttributes("a.b.c") + n1 = attrs.getNode("attr1") + n1.setType("VECTOR_COMPLEX_FLOAT") + assert n1.getType() == Types.VECTOR_COMPLEX_FLOAT + assert n1.getValue() == [(10+0j)] + n1.setValue([(1.2-3.2j), (5.4+3.3j)]) + assert n1.getValue() == [(1.2-3.2j), (5.4+3.3j)] + + # 'setType' VECTOR_COMPLEX_DOUBLE + h.setAttribute("a.b.c", "attr1", 10) + attrs = h.getAttributes("a.b.c") + n1 = attrs.getNode("attr1") + n1.setType("VECTOR_COMPLEX_DOUBLE") + assert n1.getType() == Types.VECTOR_COMPLEX_DOUBLE + assert n1.getValue() == [(10+0j)] + n1.setValue([(1.2-3.2j), (5.4+3.3j)]) + assert n1.getValue() == [(1.2-3.2j), (5.4+3.3j)] # 'setType' VECTOR_STRING h.setAttribute("a.b.c", "attr1", 10) diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_node.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_node.py index fa02405dce..104ca22d8b 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_node.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_hash_node.py @@ -15,7 +15,6 @@ # FITNESS FOR A PARTICULAR PURPOSE. from karabo.bound import Hash, HashNode, Types -from karabo.bound_tool import use_karathon def test_hashNode(): @@ -69,18 +68,16 @@ def test_hashNode(): # "test_hash_attributes_node.py" # .... skipped tests assert node.getValueAs(Types.DOUBLE) == 1.0 - if not use_karathon: - assert node.getValueAs("COMPLEX_FLOAT") == (1 + 0j) - assert node.getValueAs("COMPLEX_DOUBLE") == (1 + 0J) + assert node.getValueAs("COMPLEX_FLOAT") == (1 + 0j) + assert node.getValueAs("COMPLEX_DOUBLE") == (1 + 0J) assert node.getValueAs(Types.STRING) == '1' assert node.getValueAs(Types.VECTOR_BOOL) == [True] assert node.getValueAs(Types.VECTOR_INT16) == [1] # .... skipped tests ... - if not use_karathon: - assert node.getValueAs(Types.VECTOR_FLOAT) == [1.0] - assert node.getValueAs(Types.VECTOR_DOUBLE) == [1.0] - assert node.getValueAs(Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] - assert node.getValueAs(Types.VECTOR_COMPLEX_DOUBLE) == [(1 + 0j)] + assert node.getValueAs(Types.VECTOR_FLOAT) == [1.0] + assert node.getValueAs(Types.VECTOR_DOUBLE) == [1.0] + assert node.getValueAs(Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] + assert node.getValueAs(Types.VECTOR_COMPLEX_DOUBLE) == [(1 + 0j)] # Call is not supported ... # FIXME: VECTOR_STRING not supported in both cases @@ -98,9 +95,8 @@ def test_hashNode(): assert n.getValueAs(Types.UINT64) == 1 assert n.getValueAs(Types.FLOAT) == 1.0 assert n.getValueAs(Types.DOUBLE) == 1.0 - if not use_karathon: - assert n.getValueAs(Types.COMPLEX_FLOAT) == (1 + 0j) - assert n.getValueAs(Types.COMPLEX_DOUBLE) == (1 + 0j) + assert n.getValueAs(Types.COMPLEX_FLOAT) == (1 + 0j) + assert n.getValueAs(Types.COMPLEX_DOUBLE) == (1 + 0j) assert n.getValueAs(Types.STRING) == '1' assert n.getValueAs(Types.VECTOR_BOOL) == [True] # assert n.getValueAs(Types.VECTOR_CHAR) == ['1'] @@ -109,11 +105,10 @@ def test_hashNode(): assert n.getValueAs(Types.VECTOR_INT16) == [1] # ... skipped tests assert n.getValueAs(Types.VECTOR_UINT64) == [1] - if not use_karathon: - assert n.getValueAs(Types.VECTOR_FLOAT) == [1.0] - assert n.getValueAs(Types.VECTOR_DOUBLE) == [1.0] - assert n.getValueAs(Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] - assert n.getValueAs(Types.VECTOR_COMPLEX_DOUBLE) == [(1 + 0j)] + assert n.getValueAs(Types.VECTOR_FLOAT) == [1.0] + assert n.getValueAs(Types.VECTOR_DOUBLE) == [1.0] + assert n.getValueAs(Types.VECTOR_COMPLEX_FLOAT) == [(1 + 0j)] + assert n.getValueAs(Types.VECTOR_COMPLEX_DOUBLE) == [(1 + 0j)] # Call is not supported ... # assert n.getValueAs(Types.VECTOR_STRING) == ['1'] @@ -124,9 +119,8 @@ def test_hashNode(): assert n.getValueAs(Types.INT8) == 42 # ... skipped tests assert n.getValueAs(Types.DOUBLE) == 42 - if not use_karathon: - assert n.getValueAs(Types.COMPLEX_FLOAT) == (42 + 0j) - assert n.getValueAs(Types.COMPLEX_DOUBLE) == (42 + 0j) + assert n.getValueAs(Types.COMPLEX_FLOAT) == (42 + 0j) + assert n.getValueAs(Types.COMPLEX_DOUBLE) == (42 + 0j) assert n.getValueAs(Types.STRING) == '42' # Base64 encoding # Since we use `karabo::util::StringTools.hh` for conversion @@ -137,11 +131,10 @@ def test_hashNode(): assert n.getValueAs(Types.VECTOR_INT16) == [42] # ... skipped tests assert n.getValueAs(Types.VECTOR_UINT64) == [42] - if not use_karathon: - assert n.getValueAs(Types.VECTOR_FLOAT) == [42.0] - assert n.getValueAs(Types.VECTOR_DOUBLE) == [42.0] - assert n.getValueAs("VECTOR_COMPLEX_FLOAT") == [(42 + 0j)] - assert n.getValueAs("VECTOR_COMPLEX_DOUBLE") == [(42 + 0j)] + assert n.getValueAs(Types.VECTOR_FLOAT) == [42.0] + assert n.getValueAs(Types.VECTOR_DOUBLE) == [42.0] + assert n.getValueAs("VECTOR_COMPLEX_FLOAT") == [(42 + 0j)] + assert n.getValueAs("VECTOR_COMPLEX_DOUBLE") == [(42 + 0j)] # Call is not supported... # assert n.getValueAs(Types.VECTOR_STRING) == '42' @@ -158,21 +151,19 @@ def test_hashNode(): assert node.getAttributeAs("a", Types.INT8) == 15 # ... skipped tests assert node.getAttributeAs("a", "DOUBLE") == 15 - if not use_karathon: - assert node.getAttributeAs("a", Types.COMPLEX_FLOAT) == (15 + 0j) - assert node.getAttributeAs("a", Types.COMPLEX_DOUBLE) == (15 + 0j) + assert node.getAttributeAs("a", Types.COMPLEX_FLOAT) == (15 + 0j) + assert node.getAttributeAs("a", Types.COMPLEX_DOUBLE) == (15 + 0j) assert node.getAttributeAs("a", Types.STRING) == '15' # Base64 encoding # assert node.getAttributeAs("a", Types.VECTOR_INT8) == [15] # assert node.getAttributeAs("a", Types.VECTOR_UINT8) == [15] - if not use_karathon: - assert node.getAttributeAs("a", "VECTOR_INT16") == [15] - # ... skipped tests - assert node.getAttributeAs("a", Types.VECTOR_DOUBLE) == [15] - assert node.getAttributeAs("a", Types.VECTOR_COMPLEX_FLOAT) == [ - (15 + 0j)] - assert node.getAttributeAs("a", Types.VECTOR_COMPLEX_DOUBLE) == [ - (15 + 0j)] + assert node.getAttributeAs("a", "VECTOR_INT16") == [15] + # ... skipped tests + assert node.getAttributeAs("a", Types.VECTOR_DOUBLE) == [15] + assert node.getAttributeAs("a", Types.VECTOR_COMPLEX_FLOAT) == [ + (15 + 0j)] + assert node.getAttributeAs("a", Types.VECTOR_COMPLEX_DOUBLE) == [ + (15 + 0j)] # Not supported # assert node.getAttributeAs("a", Types.VECTOR_STRING) == ['15'] diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_json_parsing_for_init_string.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_json_parsing_for_init_string.py index 743ed037f5..f38b494bc2 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_json_parsing_for_init_string.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_json_parsing_for_init_string.py @@ -14,7 +14,7 @@ # WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. -from karabo.bound_tool import Hash, generateAutoStartHash, jsonToHash +from karabind import Hash, generateAutoStartHash, jsonToHash def test_init_string_to_auto_start_hash_conversion(): diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_api.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_api.py index 2ff80cbb5e..a503929ce3 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_api.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_api.py @@ -23,7 +23,6 @@ from karabo.bound import ( ChannelMetaData, ConnectionStatus, EventLoop, Hash, InputChannel, OutputChannel, SignalSlotable, Timestamp, Types, VectorHash) -from karabo.bound_tool import use_karathon # Enable logs for debugging - does not matter which bindings are used: # from karabo.bound import Logger @@ -259,9 +258,8 @@ def tracker(outId, status): # Write first data - nobody connected yet. meta = ChannelMetaData("outputChannel:output", Timestamp()) - if not use_karathon: - assert meta.getSource() == meta['source'] - assert meta.getTimestamp() == meta['timestamp'] + assert meta.getSource() == meta['source'] + assert meta.getTimestamp() == meta['timestamp'] out.write(Hash("key", 42), meta) out.update() diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_utils.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_utils.py index d9827e90e4..0ffd60509a 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_utils.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_pipeline_utils.py @@ -17,7 +17,6 @@ from karabo.bound import ( INPUT_CHANNEL, INT32_ELEMENT, OUTPUT_CHANNEL, ChannelMetaData, Epochstamp, Schema, Timestamp, Trainstamp) -from karabo.bound_tool import use_karathon def test_metadata_general_functionality(): @@ -30,12 +29,8 @@ def test_metadata_general_functionality(): assert meta.getTimestamp().getSeconds() == 1356441936 assert meta.getTimestamp().getFractionalSeconds() == 789333123456789123 assert meta.getTimestamp().toFormattedString() == ts.toFormattedString() - if not use_karathon: - # Equality operator is bound - assert meta.getTimestamp() == ts - else: - # Equality operator is not implemented - assert meta.getTimestamp() != ts + # Equality operator is bound + assert meta.getTimestamp() == ts meta.setSource('xyz') assert meta.getSource() != 'abc' diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_schema_elements.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_schema_elements.py index a270710315..ad97ee15fb 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_schema_elements.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_schema_elements.py @@ -19,23 +19,20 @@ import pytest from karabo.bound import ( - ALARM_ELEMENT, BOOL_ELEMENT, CHOICE_ELEMENT, DOUBLE_ELEMENT, EVERY_1S, - EVERY_100MS, EVERY_EVENT, FLOAT_ELEMENT, IMAGEDATA_ELEMENT, INT32_ELEMENT, - INT64_ELEMENT, KARABO_CLASSINFO, KARABO_CONFIGURATION_BASE_CLASS, - LIST_ELEMENT, METER, MICRO, NDARRAY_ELEMENT, NO_ARCHIVING, NODE_ELEMENT, - OVERWRITE_ELEMENT, PATH_ELEMENT, SLOT_ELEMENT, STATE_ELEMENT, - STRING_ELEMENT, TABLE_ELEMENT, UINT32_ELEMENT, UINT64_ELEMENT, - VECTOR_BOOL_ELEMENT, VECTOR_DOUBLE_ELEMENT, VECTOR_INT32_ELEMENT, - VECTOR_STRING_ELEMENT, VECTOR_UINT32_ELEMENT, AccessLevel, AccessType, - ArchivePolicy, AssemblyRules, AssignmentType, Encoding, Hash, MetricPrefix, - NodeType, Schema, Types, Unit, fullyEqual) -from karabo.bound_tool import use_karathon + ALARM_ELEMENT, BOOL_ELEMENT, BYTEARRAY_ELEMENT, CHOICE_ELEMENT, + DOUBLE_ELEMENT, EVERY_1S, EVERY_100MS, EVERY_EVENT, FLOAT_ELEMENT, + IMAGEDATA_ELEMENT, INT32_ELEMENT, INT64_ELEMENT, KARABO_CLASSINFO, + KARABO_CONFIGURATION_BASE_CLASS, LIST_ELEMENT, METER, MICRO, + NDARRAY_ELEMENT, NO_ARCHIVING, NODE_ELEMENT, OVERWRITE_ELEMENT, + PATH_ELEMENT, SLOT_ELEMENT, STATE_ELEMENT, STRING_ELEMENT, TABLE_ELEMENT, + UINT32_ELEMENT, UINT64_ELEMENT, VECTOR_BOOL_ELEMENT, VECTOR_DOUBLE_ELEMENT, + VECTOR_INT32_ELEMENT, VECTOR_STRING_ELEMENT, VECTOR_UINT32_ELEMENT, + AccessLevel, AccessType, ArchivePolicy, AssemblyRules, AssignmentType, + Encoding, Hash, MetricPrefix, NodeType, Schema, Types, Unit, cppNDArray, + cppNDArrayCopy, fullyEqual) from karabo.common.alarm_conditions import AlarmCondition from karabo.common.states import State -if not use_karathon: - from karabo.bound_tool import BYTEARRAY_ELEMENT, cppNDArray, cppNDArrayCopy - @KARABO_CONFIGURATION_BASE_CLASS @KARABO_CLASSINFO("ShapeX", "1.0") @@ -352,36 +349,35 @@ def expectedParameters(expected): .commit(), ) - if not use_karathon: - ( - # Always readOnly(), by default as well - BYTEARRAY_ELEMENT(expected) - .key("rarray") - .alias("aliasReadArray") - .tags("software") - .displayedName("Example read array") - .description("Example of ByteArray for reading") - .userAccess() - .readOnly() - .initialValue(bytes('abcdef привет 012345', 'u8')) - .commit(), - - BYTEARRAY_ELEMENT(expected) - .key("rarray1") - .displayedName("ReadArrayStr") - .adminAccess() - .readOnly() - .initialValue('hello world') - .commit(), - - BYTEARRAY_ELEMENT(expected) - .key("rarray2") - .displayedName("ReadByteArray") - .observerAccess() - .readOnly() - .initialValue(bytearray('Tschüß!', 'u8')) - .commit(), - ) + ( + # Always readOnly(), by default as well + BYTEARRAY_ELEMENT(expected) + .key("rarray") + .alias("aliasReadArray") + .tags("software") + .displayedName("Example read array") + .description("Example of ByteArray for reading") + .userAccess() + .readOnly() + .initialValue(bytes('abcdef привет 012345', 'u8')) + .commit(), + + BYTEARRAY_ELEMENT(expected) + .key("rarray1") + .displayedName("ReadArrayStr") + .adminAccess() + .readOnly() + .initialValue('hello world') + .commit(), + + BYTEARRAY_ELEMENT(expected) + .key("rarray2") + .displayedName("ReadByteArray") + .observerAccess() + .readOnly() + .initialValue(bytearray('Tschüß!', 'u8')) + .commit(), + ) ( INT64_ELEMENT(expected) @@ -1140,8 +1136,7 @@ def test_getTags(): assert schema.getTags("exampleKey4")[0] == "software" assert schema.getTags("exampleKey5")[0] == "h/w" assert schema.getTags("exampleKey5")[1] == "d.m.y" - if not use_karathon: - assert schema.getTags("rarray")[0] == "software" + assert schema.getTags("rarray")[0] == "software" def test_setTags(): @@ -1177,8 +1172,7 @@ def test_getsetAccessLevel(): assert sch.getRequiredAccessLevel('exampleKey10') == AccessLevel.USER # observerAccess in reconfigurable assert sch.getRequiredAccessLevel('exampleKey11') == AccessLevel.OBSERVER - if not use_karathon: - assert sch.getRequiredAccessLevel('rarray') == AccessLevel.USER + assert sch.getRequiredAccessLevel('rarray') == AccessLevel.USER def test_isNode(): @@ -1216,8 +1210,7 @@ def test_getValueType(): assert schema.getValueType("exampleKey7b") == Types.VECTOR_UINT32 assert schema.getValueType("exampleKey8") == Types.VECTOR_DOUBLE assert schema.getValueType("exampleKey9") == Types.VECTOR_STRING - if not use_karathon: - assert schema.getValueType("rarray") == Types.BYTE_ARRAY + assert schema.getValueType("rarray") == Types.BYTE_ARRAY def test_getAliasAsString(): @@ -1229,8 +1222,7 @@ def test_getAliasAsString(): assert schema.getAliasAsString("exampleKey5") == "exampleAlias5" assert schema.getAliasAsString("exampleKey6") == "1193046,43724" assert schema.getAliasAsString("testPath") == "5" - if not use_karathon: - assert schema.getAliasAsString("rarray") == "aliasReadArray" + assert schema.getAliasAsString("rarray") == "aliasReadArray" def test_keyHasAlias(): @@ -1243,8 +1235,7 @@ def test_keyHasAlias(): assert schema.keyHasAlias("exampleKey5") is True assert schema.keyHasAlias("exampleKey6") is True assert schema.keyHasAlias("testPath") is True - if not use_karathon: - assert schema.keyHasAlias("rarray") is True + assert schema.keyHasAlias("rarray") is True def test_aliasHasKey(): @@ -1257,8 +1248,7 @@ def test_aliasHasKey(): assert schema.aliasHasKey([0x00123456, 0x0000aacc]) is True assert schema.aliasHasKey(7) is False assert schema.aliasHasKey(5) is True - if not use_karathon: - assert schema.aliasHasKey("aliasReadArray") is True + assert schema.aliasHasKey("aliasReadArray") is True def test_getAliasFromKey(): @@ -1270,8 +1260,7 @@ def test_getAliasFromKey(): assert schema.getAliasFromKey("exampleKey5") == "exampleAlias5" assert schema.getAliasFromKey("exampleKey6") == [0x00123456, 0x0000aacc] assert schema.getAliasFromKey("testPath") == 5 - if not use_karathon: - assert schema.getAliasFromKey("rarray") == "aliasReadArray" + assert schema.getAliasFromKey("rarray") == "aliasReadArray" def test_setAlias(): @@ -1293,8 +1282,7 @@ def test_getKeyFromAlias(): assert schema.getKeyFromAlias("exampleAlias5") == "exampleKey5" assert schema.getKeyFromAlias([0x00123456, 0x0000aacc]) == "exampleKey6" assert schema.getKeyFromAlias(5) == "testPath" - if not use_karathon: - assert schema.getKeyFromAlias("aliasReadArray") == "rarray" + assert schema.getKeyFromAlias("aliasReadArray") == "rarray" def test_getAccessMode(): @@ -1310,8 +1298,7 @@ def test_getAccessMode(): assert schema.getAccessMode("testPath") == AccessType.WRITE assert schema.getAccessMode("testPath2") == AccessType.READ assert schema.getAccessMode("testPath3") == AccessType.INIT - if not use_karathon: - assert schema.getAccessMode("rarray") == AccessType.READ + assert schema.getAccessMode("rarray") == AccessType.READ def test_getAssignment(): @@ -1346,9 +1333,8 @@ def test_getDescription(): schema = Schema() TestStruct1.expectedParameters(schema) assert schema.getDescription('exampleKey1') == "Example key 1 description" - if not use_karathon: - assert schema.getDescription('rarray') == \ - "Example of ByteArray for reading" + assert schema.getDescription('rarray') == \ + "Example of ByteArray for reading" def test_setDescription(): @@ -1429,11 +1415,10 @@ def test_getDefaultValue(): # readOnly default specified by 'defaultValue'. not 'initialValue': assert schema.getDefaultValue("exampleKey5b") == 42 assert schema.getDefaultValue("exampleKey7b") == [11, 22, 33] - if not use_karathon: - assert schema.getDefaultValue("rarray") == \ - b'abcdef \xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82 012345' - assert schema.getDefaultValue("rarray1") == b'hello world' - assert schema.getDefaultValue("rarray2") == b'Tsch\xc3\xbc\xc3\x9f!' + assert schema.getDefaultValue("rarray") == \ + b'abcdef \xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82 012345' + assert schema.getDefaultValue("rarray1") == b'hello world' + assert schema.getDefaultValue("rarray2") == b'Tsch\xc3\xbc\xc3\x9f!' def test_setDefaultValue(): @@ -1981,49 +1966,48 @@ def test_allowed_actions(): s.setAllowedActions("node.int", ["bla", "blue"]) -if not use_karathon: - def test_cpp_ndarray(): - # Build numpy arrays on C++ side and convert them to the python objects - # using commented binding code below (see "karabind_test.cc") - # Conversions happen at the last step... - - # m.def("cppNDArray", []() { - # const Dims shape(3, 4); - # std::vector someData(3 * 4, 7); - # for (int i = 0; i < 3; ++i) someData[i] = 100 + i; - # NDArray nda(someData.begin(), someData.end(), shape); - # return karabind::wrapper::castNDArrayToPy(nda); - # }); - # m.def("cppNDArrayCopy", []() { - # const Dims shape(3, 4); - # std::vector someData(3 * 4, 7); - # for (int i = 0; i < 3; ++i) someData[i] = 100 + i; - # NDArray nda(someData.begin(), someData.end(), shape); - # return karabind::wrapper::copyNDArrayToPy(nda); - # }); - - # create py::array (numpy.array) objects - a = cppNDArray() - b = cppNDArrayCopy() - # These binding return the same data - assert np.all(a == b) - # The only difference between them is data ownership ... - # C++ is an owner of data array - assert a.flags.owndata is False - assert a.base is not None - # Python is an owner of data array - assert b.flags.owndata is True - assert b.base is None - assert np.all(a == b) - # this works like 'deepcopy' - c = a.copy() - assert c.flags.owndata is True - assert c.base is None - # or use deepcopy directly .. - d = copy.deepcopy(a) - assert d.flags.owndata is True - assert d.base is None - # and copy works like deepcopy - e = copy.copy(a) - assert e.flags.owndata is True - assert e.base is None +def test_cpp_ndarray(): + # Build numpy arrays on C++ side and convert them to the python objects + # using commented binding code below (see "karabind_test.cc") + # Conversions happen at the last step... + + # m.def("cppNDArray", []() { + # const Dims shape(3, 4); + # std::vector someData(3 * 4, 7); + # for (int i = 0; i < 3; ++i) someData[i] = 100 + i; + # NDArray nda(someData.begin(), someData.end(), shape); + # return karabind::wrapper::castNDArrayToPy(nda); + # }); + # m.def("cppNDArrayCopy", []() { + # const Dims shape(3, 4); + # std::vector someData(3 * 4, 7); + # for (int i = 0; i < 3; ++i) someData[i] = 100 + i; + # NDArray nda(someData.begin(), someData.end(), shape); + # return karabind::wrapper::copyNDArrayToPy(nda); + # }); + + # create py::array (numpy.array) objects + a = cppNDArray() + b = cppNDArrayCopy() + # These binding return the same data + assert np.all(a == b) + # The only difference between them is data ownership ... + # C++ is an owner of data array + assert a.flags.owndata is False + assert a.base is not None + # Python is an owner of data array + assert b.flags.owndata is True + assert b.base is None + assert np.all(a == b) + # this works like 'deepcopy' + c = a.copy() + assert c.flags.owndata is True + assert c.base is None + # or use deepcopy directly .. + d = copy.deepcopy(a) + assert d.flags.owndata is True + assert d.base is None + # and copy works like deepcopy + e = copy.copy(a) + assert e.flags.owndata is True + assert e.base is None diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_tcp.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_tcp.py index 28ff6ef818..352bc79925 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_tcp.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_tcp.py @@ -20,7 +20,6 @@ from karabo.bound import ( Broker, Connection, EventLoop, Hash, Schema, SignalSlotable, fullyEqual) -from karabo.bound_tool import use_karathon debugFlag = False lock = threading.Lock() @@ -96,9 +95,7 @@ def onConnect(ec, channel): assert alice is not None aliceConn2 = alice.getConnection() assert type(aliceConn) is Connection - if not use_karathon: - # karathon creates a new Python object here :-( - assert aliceConn2 is aliceConn + assert aliceConn2 is aliceConn # Better return (and thus keep alive) the connections as well: # C++ TcpChannel keeps only weak_ptr to its TcpConnection. @@ -154,12 +151,10 @@ def test_synch_write_read(eventLoop): alice.write(Hash("a", "header"), 1) # not supported assert "Python Exception: Not supported type" in str(excinfo.value) - if not use_karathon: - # Not sure which error we would get here with karathon - with pytest.raises(TypeError) as excinfo: - alice.write(1, "message") # not supported header type - assert ("TypeError: write(): incompatible function arguments." - in str(excinfo.value)) + with pytest.raises(TypeError) as excinfo: + alice.write(1, "message") # not supported header type + assert ("TypeError: write(): incompatible function arguments." + in str(excinfo.value)) def test_asynch_write_read(eventLoop): diff --git a/src/pythonKarabo/karabo/bound_api/tests/binding/test_zcore_device_client.py b/src/pythonKarabo/karabo/bound_api/tests/binding/test_zcore_device_client.py index fb39e09082..0bd308c193 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/binding/test_zcore_device_client.py +++ b/src/pythonKarabo/karabo/bound_api/tests/binding/test_zcore_device_client.py @@ -18,26 +18,12 @@ import uuid from threading import Thread -import pytest - -import karabind -import karathon - - -@pytest.mark.parametrize( - "EventLoop, DeviceClient, Hash, startDeviceServer, stopDeviceServer, " - "Logger", - [ - (karathon.EventLoop, karathon.DeviceClient, karathon.Hash, - karathon.startDeviceServer, karathon.stopDeviceServer, - karathon.Logger), - (karabind.EventLoop, karabind.DeviceClient, karabind.Hash, - karabind.startDeviceServer, karabind.stopDeviceServer, - karabind.Logger) - ]) -def test_device_client_sync_api(EventLoop, DeviceClient, Hash, - startDeviceServer, stopDeviceServer, - Logger): +from karabind import ( + DeviceClient, EventLoop, Hash, Logger, SignalSlotable, startDeviceServer, + stopDeviceServer) + + +def test_device_client_sync_api(): # Run CPP event loop in background ... loopThread = Thread(target=EventLoop.work) loopThread.start() @@ -119,20 +105,7 @@ def test_device_client_sync_api(EventLoop, DeviceClient, Hash, loopThread.join() -@pytest.mark.parametrize( - "EventLoop, DeviceClient, Hash, startDeviceServer, stopDeviceServer, " - "Logger", - [ - (karathon.EventLoop, karathon.DeviceClient, karathon.Hash, - karathon.startDeviceServer, karathon.stopDeviceServer, - karathon.Logger), - (karabind.EventLoop, karabind.DeviceClient, karabind.Hash, - karabind.startDeviceServer, karabind.stopDeviceServer, - karabind.Logger) - ]) -def test_device_client_async_api( - EventLoop, DeviceClient, Hash, startDeviceServer, stopDeviceServer, - Logger): +def test_device_client_async_api(): # Run CPP event loop in background ... loopThread = Thread(target=EventLoop.work) loopThread.start() @@ -194,10 +167,9 @@ def test_device_client_async_api( def test_slots_with_args(): - from karabind import DeviceClient, Hash, SignalSlotable # Run CPP event loop in background ... - loopThread = Thread(target=karabind.EventLoop.work) + loopThread = Thread(target=EventLoop.work) loopThread.start() deviceId = "slotWithArgsTester" @@ -280,5 +252,5 @@ def argSlotZahlen(digit): assert deDE == "Fünf" assert roman == "V" - karabind.EventLoop.stop() + EventLoop.stop() loopThread.join() diff --git a/src/pythonKarabo/karabo/bound_api/tests/hash_test.py b/src/pythonKarabo/karabo/bound_api/tests/hash_test.py index 3b475c52f9..2305d5e427 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/hash_test.py +++ b/src/pythonKarabo/karabo/bound_api/tests/hash_test.py @@ -25,10 +25,8 @@ import numpy as np -import karathon from karabo.bound import ( - Hash, HashMergePolicy, Types, VectorHash, fullyEqual, - isStdVectorDefaultConversion, setStdVectorDefaultConversion, similar) + Hash, HashMergePolicy, Types, VectorHash, fullyEqual, similar) from karabo.testing.utils import compare_ndarray_data_ptrs @@ -230,33 +228,6 @@ def test_getSet(self): except Exception as e: self.fail("test_getSet exception group 6: " + str(e)) - if Hash is karathon.Hash: - try: - h = Hash('a.b.c', [1, 2, 3, 4, 5, 6, 7], 'b.c.d', - [False, False, True, True, True, False, True]) - self.assertEqual(isStdVectorDefaultConversion(Types.PYTHON), - True) - self.assertEqual(h.isType('a.b.c', Types.VECTOR_INT32), True) - self.assertIsInstance(h['a.b.c'], list) - try: - setStdVectorDefaultConversion(Types.VECTOR_INT32) - except RuntimeError: - pass - self.assertEqual(isStdVectorDefaultConversion(Types.PYTHON), - True) - setStdVectorDefaultConversion(Types.NUMPY) - self.assertEqual(isStdVectorDefaultConversion(Types.PYTHON), - False) - self.assertEqual(isStdVectorDefaultConversion(Types.NUMPY), - True) - self.assertIsInstance(h['a.b.c'], np.ndarray) - self.assertIsInstance(h['b.c.d'], np.ndarray) - setStdVectorDefaultConversion(Types.PYTHON) - self.assertEqual(isStdVectorDefaultConversion(Types.PYTHON), - True) - except Exception as e: - self.fail("test_getSet exception group 7: " + str(e)) - def test_getSetVectorHash(self): try: h = Hash('a', VectorHash()) @@ -423,11 +394,9 @@ def test_intUnboxingEdgeCases(self): # h = Hash("b", 2 ** 64) # SystemError: returned a # result with an error set - exc = SystemError if Hash.__module__ == "karathon" else RuntimeError - with self.assertRaises(exc): + with self.assertRaises(RuntimeError): h = Hash("b", 2 ** 64) - exc = OverflowError if Hash.__module__ == "karathon" else RuntimeError - with self.assertRaises(exc): + with self.assertRaises(RuntimeError): h = Hash("vb", [2 ** 64]) for value, type_ in values_and_types.items(): msg = f"Failed to unbox {value}: " @@ -703,33 +672,6 @@ def test_attributes(self): except Exception as e: self.fail("test_attributes exception group 5: " + str(e)) - if Hash is karathon.Hash: - try: - h = Hash("a.b.a.b", 42) - h.setAttribute("a.b.a.b", "attr1", [1, 2, 3, 4, 5, 6, 7]) - - setStdVectorDefaultConversion(Types.PYTHON) - if isStdVectorDefaultConversion(Types.PYTHON): - self.assertEqual(h.getAttribute("a.b.a.b", "attr1"), - [1, 2, 3, 4, 5, 6, 7]) - if isStdVectorDefaultConversion(Types.NUMPY): - self.assertEqual(h.getAttribute("a.b.a.b", "attr1").all(), - np.array([1, 2, 3, 4, 5, 6, 7], - dtype=np.int32).all()) - - setStdVectorDefaultConversion(Types.NUMPY) - if isStdVectorDefaultConversion(Types.PYTHON): - self.assertEqual(h.getAttribute("a.b.a.b", "attr1"), - [1, 2, 3, 4, 5, 6, 7]) - if isStdVectorDefaultConversion(Types.NUMPY): - self.assertEqual(h.getAttribute("a.b.a.b", "attr1").all(), - np.array([1, 2, 3, 4, 5, 6, 7], - dtype=np.int32).all()) - - setStdVectorDefaultConversion(Types.PYTHON) - except Exception as e: - self.fail("test_attributes exception group 6: " + str(e)) - def test_attributes_get_copy(self): try: h = Hash("a.b.a.b", 42) diff --git a/src/pythonKarabo/karabo/bound_api/tests/metadata_test.py b/src/pythonKarabo/karabo/bound_api/tests/metadata_test.py index d2d8f5fac3..7cea48eb5c 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/metadata_test.py +++ b/src/pythonKarabo/karabo/bound_api/tests/metadata_test.py @@ -19,7 +19,6 @@ import unittest -import karathon from karabo.bound import ChannelMetaData, Epochstamp, Timestamp, Trainstamp @@ -36,10 +35,8 @@ def test_metadata_general_functionality(self): meta.getTimestamp().getFractionalSeconds() == 789333123456789123) self.assertTrue( meta.getTimestamp().toFormattedString() == ts.toFormattedString()) - if ChannelMetaData is karathon.ChannelMetaData: - self.assertFalse(meta.getTimestamp() == ts) - else: - self.assertTrue(meta.getTimestamp() == ts) + + self.assertTrue(meta.getTimestamp() == ts) meta.setSource('xyz') self.assertFalse(meta.getSource() == 'abc') diff --git a/src/pythonKarabo/karabo/bound_api/tests/signal_slotable_test.py b/src/pythonKarabo/karabo/bound_api/tests/signal_slotable_test.py index 697643e1bd..0b17c3f828 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/signal_slotable_test.py +++ b/src/pythonKarabo/karabo/bound_api/tests/signal_slotable_test.py @@ -16,7 +16,7 @@ from threading import Condition, Lock, Thread from unittest import TestCase, main -from karathon import EventLoop, SignalSlotable +from karabind import EventLoop, SignalSlotable class Tests(TestCase): @@ -112,7 +112,7 @@ def test_type_handle(self): class SimpleType: pass - with self.assertRaises(RuntimeError): + with self.assertRaises(TypeError): self.call_and_compare(SimpleType()) # XXX: Additional tests need to be added (e.g. test Hash, ...). diff --git a/src/pythonKarabo/karabo/bound_api/tests/statistical_evaluator_test.py b/src/pythonKarabo/karabo/bound_api/tests/statistical_evaluator_test.py index b3bc842ab3..01890dbe37 100644 --- a/src/pythonKarabo/karabo/bound_api/tests/statistical_evaluator_test.py +++ b/src/pythonKarabo/karabo/bound_api/tests/statistical_evaluator_test.py @@ -15,7 +15,6 @@ # FITNESS FOR A PARTICULAR PURPOSE. import unittest -import karathon from karabo.bound import RollingWindowStatistics @@ -72,10 +71,7 @@ def test_rolling_window_statistics_non_empty_interval(self): def test_rolling_window_statistics_no_copy(self): import copy stat = RollingWindowStatistics(10) - if RollingWindowStatistics is karathon.RollingWindowStatistics: - self.assertRaises(RuntimeError, copy.copy, stat) - else: - self.assertRaises(TypeError, copy.copy, stat) + self.assertRaises(TypeError, copy.copy, stat) if __name__ == '__main__': diff --git a/src/pythonKarabo/karabo/bound_tool.py b/src/pythonKarabo/karabo/bound_tool.py deleted file mode 100644 index 36d52ac16e..0000000000 --- a/src/pythonKarabo/karabo/bound_tool.py +++ /dev/null @@ -1,125 +0,0 @@ -# This file is part of Karabo. -# -# http://www.karabo.eu -# -# Copyright (C) European XFEL GmbH Schenefeld. All rights reserved. -# -# Karabo is free software: you can redistribute it and/or modify it under -# the terms of the MPL-2 Mozilla Public License. -# -# You should have received a copy of the MPL-2 Public License along with -# Karabo. If not, see . -# -# Karabo is distributed in the hope that it will be useful, but WITHOUT ANY -# WARRANTY; without even the implied warranty of MERCHANTABILITY or -# FITNESS FOR A PARTICULAR PURPOSE. -# flake8: noqa: F401 -""" This module provides all the bound API names which a Device might need. -""" -import os - -use_karathon = 'USE_KARATHON' in os.environ - -if use_karathon: - from karathon import ( - ADMIN, ALARM_ELEMENT, AMPERE, AMPERE_PER_SECOND, ATTO, ATTOSEC, BAR, - BAYER, BECQUEREL, BGR, BGRA, BIT, BMP, BOOL_ELEMENT, BYTE, - BYTEARRAY_ELEMENT, CANDELA, CENTI, CHOICE_ELEMENT, CHOICE_OF_NODES, - CMYK, COMMAND, COULOMB, COUNT, DAY, DECA, DECI, DEGREE, DEGREE_CELSIUS, - DOUBLE_ELEMENT, ELECTRONVOLT, EVERY_1MIN, EVERY_1S, EVERY_5S, - EVERY_10MIN, EVERY_10S, EVERY_100MS, EVERY_EVENT, EXA, EXPERT, FARAD, - FEMTO, FEMTOSEC, FLOAT_ELEMENT, GIGA, GRAM, GRAY, HECTO, HENRY, HERTZ, - HOUR, IMAGEDATA_ELEMENT, INIT, INPUT_CHANNEL, INPUT_ELEMENT, - INT32_ELEMENT, INT64_ELEMENT, INTERNAL, JOULE, JPEG, KATAL, KELVIN, - KILO, LEAF, LIST_ELEMENT, LIST_OF_NODES, LUMEN, LUX, MANDATORY, MEGA, - METER, METER_PER_SECOND, MICRO, MICROSEC, MILLI, MILLISEC, MINUTE, - MOLE, NANO, NANOSEC, NDARRAY_ELEMENT, NEWTON, NO_ARCHIVING, NODE, - NODE_ELEMENT, NONE, NOT_ASSIGNED, NUMBER, OBSERVER, OHM, ONESECOND, - OPERATOR, OPTIONAL, OUTPUT_CHANNEL, OUTPUT_ELEMENT, OVERWRITE_ELEMENT, - PASCAL, PATH_ELEMENT, PERCENT, PETA, PICO, PICOSEC, PIXEL, PNG, - PROPERTY, RADIAN, READ, RGB, RGBA, SECOND, SIEMENS, SIEVERT, - SLOT_ELEMENT, STATE_ELEMENT, STERADIAN, STRING_ELEMENT, TABLE_ELEMENT, - TERA, TESLA, TIFF, TIME_UNITS, UINT32_ELEMENT, UINT64_ELEMENT, - UNDEFINED, USER, VECTOR_BOOL_ELEMENT, VECTOR_CHAR_ELEMENT, - VECTOR_DOUBLE_ELEMENT, VECTOR_FLOAT_ELEMENT, VECTOR_INT32_ELEMENT, - VECTOR_INT64_ELEMENT, VECTOR_STRING_ELEMENT, VECTOR_UINT32_ELEMENT, - VECTOR_UINT64_ELEMENT, VOLT, VOLT_PER_SECOND, WATT, WEBER, WRITE, YEAR, - YOCTO, YOTTA, YUV, ZEPTO, ZETTA, AbstractInput, AccessLevel, - AccessType, ArchivePolicy, AssemblyRules, AssignmentType, - BinarySerializerHash, BinarySerializerSchema, Broker, Category, - Channel, ChannelMetaData, ClassInfo, Connection, ConnectionStatus, - DaqDataType, DAQPolicy, DateTimeString, - DeviceClient as BoundDeviceClient, Dims, Encoding, Epochstamp, - ErrorCode, EventLoop, Hash, HashAttributes, HashAttributesNode, - HashFilter, HashMergePolicy, HashNode, ImageData, InputChannel, - InputHash, InputSchema, LeafType, Logger, MetricPrefix, NodeType, - OutputChannel, OutputHash, OutputSchema, Priority, PriorityLevel, - Requestor, RollingWindowStatistics, Rotation, Schema, SignalSlotable, - SignalSlotableIntern, Slot, SlotElementBase, TextSerializerHash, - TextSerializerSchema, TimeDuration, Timestamp, Trainstamp, Types, - TypesClass, Unit, Validator, ValidatorValidationRules, VectorHash, - VectorHashPointer, _DimsIntern, fullyEqual, generateAutoStartHash, - isStdVectorDefaultConversion, jsonToHash, loadFromFile, - loadHashFromFile, loadSchemaFromFile, saveHashToFile, saveSchemaToFile, - saveToFile, setDims, setStdVectorDefaultConversion, similar, - startDeviceServer, stopDeviceServer) -else: - from karabind import ( - ADMIN, ALARM_ELEMENT, AMPERE, AMPERE_PER_SECOND, ATTO, ATTOSEC, BAR, - BAYER, BECQUEREL, BGR, BGRA, BIT, BMP, BOOL_ELEMENT, BYTE, - BYTEARRAY_ELEMENT, CANDELA, CENTI, CHOICE_ELEMENT, CHOICE_OF_NODES, - CMYK, COMMAND, COULOMB, COUNT, DAY, DECA, DECI, DEGREE, DEGREE_CELSIUS, - DOUBLE_ELEMENT, ELECTRONVOLT, EVERY_1MIN, EVERY_1S, EVERY_5S, - EVERY_10MIN, EVERY_10S, EVERY_100MS, EVERY_EVENT, EXA, EXPERT, FARAD, - FEMTO, FEMTOSEC, FLOAT_ELEMENT, GIGA, GRAM, GRAY, HECTO, HENRY, HERTZ, - HOUR, IMAGEDATA_ELEMENT, INIT, INPUT_CHANNEL, INPUT_ELEMENT, - INT32_ELEMENT, INT64_ELEMENT, INTERNAL, JOULE, JPEG, KATAL, KELVIN, - KILO, LEAF, LIST_ELEMENT, LIST_OF_NODES, LUMEN, LUX, MANDATORY, MEGA, - METER, METER_PER_SECOND, MICRO, MICROSEC, MILLI, MILLISEC, MINUTE, - MOLE, NANO, NANOSEC, NDARRAY_ELEMENT, NEWTON, NO_ARCHIVING, NODE, - NODE_ELEMENT, NONE, NOT_ASSIGNED, NUMBER, OBSERVER, OHM, ONESECOND, - OPERATOR, OPTIONAL, OUTPUT_CHANNEL, OUTPUT_ELEMENT, OVERWRITE_ELEMENT, - PASCAL, PATH_ELEMENT, PERCENT, PETA, PICO, PICOSEC, PIXEL, PNG, - PROPERTY, RADIAN, READ, RGB, RGBA, SECOND, SIEMENS, SIEVERT, - SLOT_ELEMENT, STATE_ELEMENT, STERADIAN, STRING_ELEMENT, TABLE_ELEMENT, - TERA, TESLA, TIFF, TIME_UNITS, UINT32_ELEMENT, UINT64_ELEMENT, - UNDEFINED, USER, VECTOR_BOOL_ELEMENT, VECTOR_CHAR_ELEMENT, - VECTOR_DOUBLE_ELEMENT, VECTOR_FLOAT_ELEMENT, VECTOR_INT32_ELEMENT, - VECTOR_INT64_ELEMENT, VECTOR_STRING, VECTOR_STRING_ELEMENT, - VECTOR_UINT32_ELEMENT, VECTOR_UINT64_ELEMENT, VOLT, VOLT_PER_SECOND, - WATT, WEBER, WRITE, YEAR, YOCTO, YOTTA, YUV, ZEPTO, ZETTA, AccessLevel, - AccessType, ArchivePolicy, AssemblyRules, AssignmentType, - BinarySerializerHash, BinarySerializerSchema, Broker, Category, - Channel, ChannelMetaData, ClassInfo, Connection, ConnectionStatus, - DaqDataType, DAQPolicy, DateTimeString, - DeviceClient as BoundDeviceClient, Dims, Encoding, Epochstamp, - ErrorCode, EventLoop, Hash, HashAttributes, HashAttributesNode, - HashFilter, HashMergePolicy, HashNode, ImageData, InputChannel, - InputHash, InputSchema, LeafType, Logger, MetricPrefix, NodeType, - OutputChannel, OutputHash, OutputSchema, Priority, PriorityLevel, - Requestor, RollingWindowStatistics, Rotation, Schema, SignalSlotable, - SignalSlotableIntern, Slot, SlotElementBase, TextSerializerHash, - TextSerializerSchema, TimeDuration, Timestamp, Trainstamp, Types, - TypesClass, Unit, Validator, ValidatorValidationRules, VectorHash, - VectorHashPointer, _DimsIntern, cppNDArray, cppNDArrayCopy, fullyEqual, - generateAutoStartHash, jsonToHash, loadFromFile, loadHashFromFile, - loadSchemaFromFile, saveHashToFile, saveSchemaToFile, saveToFile, - setDims, similar, startDeviceServer, stopDeviceServer) - - # For comptibility with old karathon bindings, take care that e.g. - # str(Types.INT32) is 'INT32' and not 'Types.INT32' - def __typesToString(self): - repStr = repr(self) # i.e. '' - return repStr[7:repStr.find(':')] - - setattr(Types, "__str__", __typesToString) - - - class AbstractInput: - pass - - def isStdVectorDefaultConversion(): - return True - - def setStdVectorDefaultConversion(): - pass diff --git a/src/pythonKarabo/karabo/integration_tests/device_cross_test/test_cross.py b/src/pythonKarabo/karabo/integration_tests/device_cross_test/test_cross.py index fc637ca981..e3875a70f1 100644 --- a/src/pythonKarabo/karabo/integration_tests/device_cross_test/test_cross.py +++ b/src/pythonKarabo/karabo/integration_tests/device_cross_test/test_cross.py @@ -62,6 +62,7 @@ class ImageChannel(Configurable): class MiddlelayerDevice(DeviceClientBase): + """A simple device with topology info""" channelcount = 0 rawchannelcount = 0