Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
openSUSE:Backports:SLE-15-SP1:Update
libArcus-lulzbot
libArcus-3.2.20.obscpio
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File libArcus-3.2.20.obscpio of Package libArcus-lulzbot
07070100833186000081A4000003E800000064000000015A702007000001D0000000080000000200000000000000000000002500000000libArcus-3.2.20/ArcusConfig.cmake.in@PACKAGE_INIT@ # We want to have access to protobuf_generate_cpp and other FindProtobuf features. # However, if ProtobufConfig is used instead, there is a CMake option that controls # this, which defaults to OFF. We need to force this option to ON instead. set(protobuf_MODULE_COMPATIBLE ON CACHE "" INTERNAL FORCE) find_package(Protobuf 3.0.0 REQUIRED) get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) include(${SELF_DIR}/Arcus-targets.cmake) 0707010083316D000081A4000003E800000064000000015A70200700001323000000080000000200000000000000000000001F00000000libArcus-3.2.20/CMakeLists.txtproject(arcus) cmake_minimum_required(VERSION 2.8.12) include(GNUInstallDirs) include(CMakePackageConfigHelpers) option(BUILD_PYTHON "Build " ON) option(BUILD_EXAMPLES "Build the example programs" ON) option(BUILD_STATIC "Build as a static library" OFF) option(MSVC_STATIC_RUNTIME "Link the MSVC runtime statically" OFF) # We want to have access to protobuf_generate_cpp and other FindProtobuf features. # However, if ProtobufConfig is used instead, there is a CMake option that controls # this, which defaults to OFF. We need to force this option to ON instead. set(protobuf_MODULE_COMPATIBLE ON CACHE "" INTERNAL FORCE) find_package(Protobuf 3.0.0 REQUIRED) set(CMAKE_POSITION_INDEPENDENT_CODE ON) #Required if a patch to libArcus needs to be made via templates. if(BUILD_PYTHON) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) find_package(SIP REQUIRED) if(NOT DEFINED LIB_SUFFIX) set(LIB_SUFFIX "") endif() if(EXISTS /etc/debian_version) # Running on a debian-based system, which requires special handling for python modules. set(PYTHON_SITE_PACKAGES_DIR lib${LIB_SUFFIX}/python3/dist-packages CACHE STRING "Directory to install Python bindings to") else() set(PYTHON_SITE_PACKAGES_DIR lib${LIB_SUFFIX}/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages CACHE STRING "Directory to install Python bindings to") endif() include_directories(python/ src/ ${SIP_INCLUDE_DIR} ${PYTHON_INCLUDE_DIR}) endif() if(NOT ${CMAKE_VERSION} VERSION_LESS 3.1) set(CMAKE_CXX_STANDARD 11) else() set(CMAKE_CXX_FLAGS "-std=c++11") endif() if(APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++") endif() set(arcus_SRCS src/Socket.cpp src/SocketListener.cpp src/MessageTypeStore.cpp src/PlatformSocket.cpp src/Error.cpp ) set(arcus_HDRS src/Socket.h src/SocketListener.h src/Types.h src/ArcusExport.h src/MessageTypeStore.h src/Error.h ) set(ARCUS_VERSION 1.1.0) set(ARCUS_SOVERSION 3) set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") if(BUILD_STATIC) add_library(Arcus STATIC ${arcus_SRCS}) if(NOT WIN32 OR CMAKE_COMPILER_IS_GNUCXX) target_link_libraries(Arcus PRIVATE pthread) set_target_properties(Arcus PROPERTIES COMPILE_FLAGS -fPIC) endif() else() add_library(Arcus SHARED ${arcus_SRCS}) endif() if(MSVC_STATIC_RUNTIME) foreach(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) if(${flag_var} MATCHES "/MD") string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") endif(${flag_var} MATCHES "/MD") endforeach(flag_var) endif() if(BUILD_PYTHON) set(SIP_EXTRA_FILES_DEPEND python/SocketListener.sip python/Types.sip python/PythonMessage.sip python/Error.sip) set(SIP_EXTRA_SOURCE_FILES python/PythonMessage.cpp) set(SIP_EXTRA_OPTIONS -g) # -g means always release the GIL before calling C++ methods. add_sip_python_module(Arcus python/Socket.sip Arcus) endif() target_include_directories(Arcus PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> ${PROTOBUF_INCLUDE_DIR} ) target_link_libraries(Arcus PUBLIC ${PROTOBUF_LIBRARIES}) if(WIN32) add_definitions(-D_hypot=hypot) # Let's try to fix "error: '::hypot' has not been declared" add_definitions(-D_WIN32_WINNT=0x0600) # Declare we require Vista or higher, this allows us to use IPv6 functions. target_link_libraries(Arcus PUBLIC Ws2_32) endif() if(${CMAKE_BUILD_TYPE}) if(${CMAKE_BUILD_TYPE} STREQUAL "Debug" OR ${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") add_definitions(-DARCUS_DEBUG) endif() endif() set_target_properties(Arcus PROPERTIES FRAMEWORK FALSE VERSION ${ARCUS_VERSION} SOVERSION ${ARCUS_SOVERSION} PUBLIC_HEADER "${arcus_HDRS}" DEFINE_SYMBOL MAKE_ARCUS_LIB ) if(BUILD_EXAMPLES) add_subdirectory(examples) endif() install(TARGETS Arcus EXPORT Arcus-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/Arcus ) install(EXPORT Arcus-targets DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) configure_package_config_file(ArcusConfig.cmake.in ${CMAKE_BINARY_DIR}/ArcusConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus) write_basic_package_version_file(${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake VERSION ${ARCUS_VERSION} COMPATIBILITY SameMajorVersion) install(FILES ${CMAKE_BINARY_DIR}/ArcusConfig.cmake ${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) include(CPackConfig.cmake) 0707010083317D000081A4000003E800000064000000015A70200700000383000000080000000200000000000000000000002200000000libArcus-3.2.20/CPackConfig.cmakeset(CPACK_PACKAGE_VENDOR "Ultimaker") set(CPACK_PACKAGE_CONTACT "Arjen Hiemstra <a.hiemstra@ultimaker.com>") set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "libArcus Communication library") if(NOT DEFINED CPACK_PACKAGE_VERSION) set(CPACK_PACKAGE_VERSION "15.05.91") endif() set(CPACK_GENERATOR "DEB") if(NOT DEFINED CPACK_DEBIAN_PACKAGE_ARCHITECTURE) execute_process(COMMAND dpkg --print-architecture OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE OUTPUT_STRIP_TRAILING_WHITESPACE) endif() set(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${CPACK_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}") set(DEB_DEPENDS "python3 (>= 3.4.0)" "libgcc1 (>= 4.9.0)" "libstdc++6 (>= 4.9.0)" "libc6 (>= 2.19)" "zlib1g (>= 1.2.0)" "python3-protobuf (>= 3.0.0)" ) string(REPLACE ";" ", " DEB_DEPENDS "${DEB_DEPENDS}") set(CPACK_DEBIAN_PACKAGE_DEPENDS ${DEB_DEPENDS}) include(CPack) 07070100833163000081A4000003E800000064000000015A702007000003FC000000080000000200000000000000000000001C00000000libArcus-3.2.20/Jenkinsfileparallel_nodes(["linux && cura", "windows && cura"]) { stage('Prepare') { step([$class: 'WsCleanup']) checkout scm } catchError { dir('build') { stage('Build') { def branch = env.BRANCH_NAME if(!fileExists("${env.CURA_ENVIRONMENT_PATH}/${branch}")) { branch = "master" } def extra_cmake_options = "" if(!isUnix()) { // Disable building of Python bindings on Windows for now, // since it requires MSVC to build properly. extra_cmake_options = "-DBUILD_PYTHON=OFF" } cmake '..', "-DCMAKE_PREFIX_PATH=\"${env.CURA_ENVIRONMENT_PATH}/${branch}\" -DCMAKE_BUILD_TYPE=Release ${extra_cmake_options}" make('') } } } stage('Finalize') { notify_build_result(env.CURA_EMAIL_RECIPIENTS, '#cura-dev', ['master']) } } 07070100833162000081A4000003E800000064000000015A70200700001DD3000000080000000200000000000000000000001800000000libArcus-3.2.20/LICENSE GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.0707010083316E000081A4000003E800000064000000015A70200700000C75000000080000000200000000000000000000001A00000000libArcus-3.2.20/README.mdArcus ===== This library contains C++ code and Python3 bindings for creating a socket in a thread and using this socket to send and receive messages based on the Protocol Buffers library. It is designed to facilitate the communication between Cura and its backend and similar code. Building ======== To build the library, the following packages are needed: * [Protobuf 3](https://github.com/google/protobuf) (3.0+) * [CMake](https://www.cmake.org) To build the python bindings (default on, disable with -DBUILD_PYTHON=OFF) these additional libries are needed: * python3-dev (3.4+) * python3-sip-dev (4.16+) Building the library can be done with: - ```$ mkdir build && cd build``` - ```$ cmake ..``` - ```$ make``` - ```# make install``` This will install to CMake's default install prefix, ```/usr/local```. To change the prefix, set ```CMAKE_INSTALL_PREFIX```. By default, the examples directory is also built. To disable this, set BUILD_EXAMPLES to off. To disable building the Python bindings, set BUILD_PYTHON to OFF. They will be installed into ```$prefix/lib/python3/dist-packages``` on Debian-based systems and into ```$prefix/lib/python3.4/site-packages``` on other computers. To override this directory, set ```PYTHON_SITE_PACKAGES_DIR```. Building the Python bindings on 64-bit Windows requires you to build with Microsoft Visual C++ since the module will fail to import if built with MinGW. Using the Socket ================ The socket assumes a very simple and strict wire protocol: one 32-bit integer with a header, one 32-bit integer with the message size, one 32-bit integer with a type id then a byte array containing the message as serialized by Protobuf. The receiving side checks for these fields and will deserialize the message, after which it can be processed by the application. To send or receive messages, the message first needs to be registered on both sides with a call to `registerMessageType()`. You can also register all messages from a Protobuf .proto file with a call to `registerAllMessageTypes()`. For the Python bindings, this is the only supported way of registering since there are no Python classses for individual message types. The Python bindings expose the same API as the Public C++ API, except for the missing `registerMessageType()` and the individual messages. The Python bindings wrap the messages in a class that exposes the message's properties as Python properties, and can thus be set the same way you would set any other Python property. The exception is repeated fields. Currently, only repeated messages are supported, which can be created through the `addRepeatedMessage()` method. `repeatedMessageCount()` will return the number of repeated messages on an object and `getRepeatedMessage()` will get a certain instance of a repeated message. See python/PythonMessage.h for more details. Origin of the Name ================== The name Arcus is from the Roman god Arcus. This god is the roman equivalent of the goddess Iris, who is the personification of the rainbow and the messenger of the gods. Java ==== There is a Java port of libArcus, which can be found [here](https://github.com/Ocarthon/libArcus-Java). 07070100833185000081A4000003E800000064000000015A70200700000134000000080000000200000000000000000000001800000000libArcus-3.2.20/TODO.mdThings to add later =================== - Support for Unix file sockets in addition to streamed local TCP sockets. - Support for DNS resolving. - Find some way to unit test this. - Use a hash function on the message type name to automatically determine message type id. - Improve error handling / checking. 0707010083E16F000041ED000003E800000064000000025A70200700000000000000080000000200000000000000000000001600000000libArcus-3.2.20/cmake07070100833164000081A4000003E800000064000000015A7020070000052F000000080000000200000000000000000000002C00000000libArcus-3.2.20/cmake/COPYING-CMAKE-SCRIPTSRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 07070100833167000081A4000003E800000064000000015A702007000009B9000000080000000200000000000000000000002400000000libArcus-3.2.20/cmake/FindSIP.cmake# Find SIP # ~~~~~~~~ # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # Find the installed version of SIP. FindSIP should be called after Python # has been found. # # This file defines the following variables: # # SIP_VERSION - The version of SIP found expressed as a 6 digit hex number # suitable for comparision as a string. # # SIP_VERSION_STR - The version of SIP found as a human readable string. # # SIP_BINARY_PATH - Path and filename of the SIP command line executable. # # SIP_INCLUDE_DIR - Directory holding the SIP C++ header file. # # SIP_DEFAULT_SIP_DIR - Default directory where .sip files should be installed # into. # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(APPLE) # Workaround for broken FindPythonLibs. It will always find Python 2.7 libs on OSX set(CMAKE_FIND_FRAMEWORK LAST) endif() find_package(PythonInterp 3.4.0 REQUIRED) find_package(PythonLibs 3.4.0 REQUIRED) IF(SIP_VERSION) # Already in cache, be silent SET(SIP_FOUND TRUE) ELSE(SIP_VERSION) FIND_FILE(_find_sip_py FindSIP.py PATHS ${CMAKE_MODULE_PATH}) SET(ENV{PYTHONPATH} ${CMAKE_INSTALL_PREFIX}/${PYTHON_SITE_PACKAGES_DIR}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_sip_py} OUTPUT_VARIABLE sip_config RESULT_VARIABLE sip_config_returncode) IF(sip_config_returncode EQUAL 0) STRING(REGEX REPLACE "^sip_version:([^\n]+).*$" "\\1" SIP_VERSION ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_num:([^\n]+).*$" "\\1" SIP_VERSION_NUM ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_str:([^\n]+).*$" "\\1" SIP_VERSION_STR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_bin:([^\n]+).*$" "\\1" SIP_BINARY_PATH ${sip_config}) STRING(REGEX REPLACE ".*\ndefault_sip_dir:([^\n]+).*$" "\\1" SIP_DEFAULT_SIP_DIR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_inc_dir:([^\n]+).*$" "\\1" SIP_INCLUDE_DIR ${sip_config}) SET(SIP_FOUND TRUE) ENDIF(sip_config_returncode EQUAL 0) IF(SIP_FOUND) IF(NOT SIP_FIND_QUIETLY) MESSAGE(STATUS "Found SIP version: ${SIP_VERSION_STR}") ENDIF(NOT SIP_FIND_QUIETLY) include(${CMAKE_MODULE_PATH}/SIPMacros.cmake) ELSE(SIP_FOUND) IF(SIP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find SIP") ENDIF(SIP_FIND_REQUIRED) ENDIF(SIP_FOUND) ENDIF(SIP_VERSION) 07070100833166000081A4000003E800000064000000015A70200700000847000000080000000200000000000000000000002100000000libArcus-3.2.20/cmake/FindSIP.py# FindSIP.py # # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. import sys import os.path def fail(msg="Unable to determine your sip configuration."): print(msg) sys.exit(1) try: # Try the old sipconfig. Many Linux distros still ship this in their packages. import sipconfig sipcfg = sipconfig.Configuration() sip_version = sipcfg.sip_version sip_version = sipcfg.sip_version sip_version_str = sipcfg.sip_version_str sip_bin = sipcfg.sip_bin default_sip_dir = sipcfg.default_sip_dir sip_inc_dir = sipcfg.sip_inc_dir except ImportError: try: if sys.platform == "win32": # Collect the info from the sip module and guess the rest. import sip from distutils import sysconfig sip_version = sip.SIP_VERSION sip_version_str = sip.SIP_VERSION_STR exe = sys.executable if exe is None: fail() base_path = os.path.dirname(exe) sip_bin = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\sip.exe") if not os.path.exists(sip_bin): fail() sip_inc_dir = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\include\\") if not os.path.exists(sip_inc_dir): fail() default_sip_dir = os.path.join(base_path, "Lib\\site-packages\\PyQt5\\sip\\") if not os.path.exists(default_sip_dir): fail() else: fail("Unable to import sipconfig and determine your sip configuration.") except ImportError: fail("Unable to import sipconfig and determine your sip configuration.") print("sip_version:%06.0x" % sip_version) print("sip_version_num:%d" % sip_version) print("sip_version_str:%s" % sip_version_str) print("sip_bin:%s" % sip_bin) print("default_sip_dir:%s" % default_sip_dir) print("sip_inc_dir:%s" % sip_inc_dir) 07070100833165000081A4000003E800000064000000015A702007000014E1000000080000000200000000000000000000002600000000libArcus-3.2.20/cmake/SIPMacros.cmake# Macros for SIP # ~~~~~~~~~~~~~~ # Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # This file defines the following macros: # # ADD_SIP_PYTHON_MODULE (MODULE_NAME MODULE_SIP [library1, libaray2, ...]) # Specifies a SIP file to be built into a Python module and installed. # MODULE_NAME is the name of Python module including any path name. (e.g. # os.sys, Foo.bar etc). MODULE_SIP the path and filename of the .sip file # to process and compile. libraryN are libraries that the Python module, # which is typically a shared library, should be linked to. The built # module will also be install into Python's site-packages directory. # # The behaviour of the ADD_SIP_PYTHON_MODULE macro can be controlled by a # number of variables: # # SIP_INCLUDES - List of directories which SIP will scan through when looking # for included .sip files. (Corresponds to the -I option for SIP.) # # SIP_TAGS - List of tags to define when running SIP. (Corresponds to the -t # option for SIP.) # # SIP_CONCAT_PARTS - An integer which defines the number of parts the C++ code # of each module should be split into. Defaults to 8. (Corresponds to the # -j option for SIP.) # # SIP_DISABLE_FEATURES - List of feature names which should be disabled # running SIP. (Corresponds to the -x option for SIP.) # # SIP_EXTRA_OPTIONS - Extra command line options which should be passed on to # SIP. SET(SIP_INCLUDES) SET(SIP_TAGS) SET(SIP_CONCAT_PARTS 8) SET(SIP_DISABLE_FEATURES) SET(SIP_EXTRA_OPTIONS) MACRO(ADD_SIP_PYTHON_MODULE MODULE_NAME MODULE_SIP) SET(EXTRA_LINK_LIBRARIES ${ARGN}) STRING(REPLACE "." "/" _x ${MODULE_NAME}) GET_FILENAME_COMPONENT(_parent_module_path ${_x} PATH) GET_FILENAME_COMPONENT(_child_module_name ${_x} NAME) GET_FILENAME_COMPONENT(_module_path ${MODULE_SIP} PATH) GET_FILENAME_COMPONENT(_abs_module_sip ${MODULE_SIP} ABSOLUTE) # We give this target a long logical target name. # (This is to avoid having the library name clash with any already # install library names. If that happens then cmake dependency # tracking get confused.) STRING(REPLACE "." "_" _logical_name ${MODULE_NAME}) SET(_logical_name "python_module_${_logical_name}") FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_module_path}) # Output goes in this dir. SET(_sip_includes) FOREACH (_inc ${SIP_INCLUDES}) GET_FILENAME_COMPONENT(_abs_inc ${_inc} ABSOLUTE) LIST(APPEND _sip_includes -I ${_abs_inc}) ENDFOREACH (_inc ) SET(_sip_tags) FOREACH (_tag ${SIP_TAGS}) LIST(APPEND _sip_tags -t ${_tag}) ENDFOREACH (_tag) SET(_sip_x) FOREACH (_x ${SIP_DISABLE_FEATURES}) LIST(APPEND _sip_x -x ${_x}) ENDFOREACH (_x ${SIP_DISABLE_FEATURES}) SET(_message "-DMESSAGE=Generating CPP code for module ${MODULE_NAME}") SET(_sip_output_files) FOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) IF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) SET(_sip_output_files ${_sip_output_files} ${CMAKE_CURRENT_BINARY_DIR}/${_module_path}/sip${_child_module_name}part${CONCAT_NUM}.cpp ) ENDIF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) ENDFOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) # Suppress warnings IF(PEDANTIC) IF(MSVC) # 4996 deprecation warnings (bindings re-export deprecated methods) # 4701 potentially uninitialized variable used (sip generated code) # 4702 unreachable code (sip generated code) ADD_DEFINITIONS( /wd4996 /wd4701 /wd4702 ) ELSE(MSVC) # disable all warnings ADD_DEFINITIONS( -w ) ENDIF(MSVC) ENDIF(PEDANTIC) ADD_CUSTOM_COMMAND( OUTPUT ${_sip_output_files} COMMAND ${CMAKE_COMMAND} -E echo ${message} COMMAND ${CMAKE_COMMAND} -E touch ${_sip_output_files} COMMAND ${SIP_BINARY_PATH} ${_sip_tags} ${_sip_x} ${SIP_EXTRA_OPTIONS} -j ${SIP_CONCAT_PARTS} -c ${CMAKE_CURRENT_BINARY_DIR}/${_module_path} ${_sip_includes} ${_abs_module_sip} DEPENDS ${_abs_module_sip} ${SIP_EXTRA_FILES_DEPEND} ) # not sure if type MODULE could be uses anywhere, limit to cygwin for now IF (CYGWIN OR APPLE) ADD_LIBRARY(${_logical_name} MODULE ${_sip_output_files} ${SIP_EXTRA_SOURCE_FILES}) ELSE (CYGWIN OR APPLE) ADD_LIBRARY(${_logical_name} SHARED ${_sip_output_files} ${SIP_EXTRA_SOURCE_FILES}) ENDIF (CYGWIN OR APPLE) IF (NOT APPLE) TARGET_LINK_LIBRARIES(${_logical_name} ${PYTHON_LIBRARIES}) ENDIF (NOT APPLE) TARGET_LINK_LIBRARIES(${_logical_name} ${EXTRA_LINK_LIBRARIES}) IF (APPLE) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES LINK_FLAGS "-undefined dynamic_lookup") ENDIF (APPLE) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES PREFIX "" OUTPUT_NAME ${_child_module_name}) IF (WIN32) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES SUFFIX ".pyd" IMPORT_PREFIX "_") ENDIF (WIN32) INSTALL(TARGETS ${_logical_name} DESTINATION "${PYTHON_SITE_PACKAGES_DIR}/${_parent_module_path}") ENDMACRO(ADD_SIP_PYTHON_MODULE) 0707010083E170000041ED000003E800000064000000025A70200700000000000000080000000200000000000000000000001900000000libArcus-3.2.20/examples0707010083316A000081A4000003E800000064000000015A7020070000035A000000080000000200000000000000000000002800000000libArcus-3.2.20/examples/CMakeLists.txt include_directories(example ${CMAKE_CURRENT_BINARY_DIR}) set(example_SRCS example.cpp example_pb2.py ) protobuf_generate_cpp(example_PB_SRCS example_PB_HDRS "example.proto") add_executable(example ${example_SRCS} ${example_PB_SRCS}) target_link_libraries(example Arcus) if(NOT WIN32 OR CMAKE_COMPILER_IS_GNUCXX) target_link_libraries(example pthread) set_target_properties(example PROPERTIES COMPILE_FLAGS "-std=c++11") endif() add_custom_command( OUTPUT example_pb2.py COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} ARGS --python_out ${CMAKE_CURRENT_BINARY_DIR} --proto_path=${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/example.proto COMMENT "Running Python protocol buffer compiler on example.proto" VERBATIM ) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/example_py.sh ${CMAKE_CURRENT_BINARY_DIR}/example_py.sh) 0707010083316C000081A4000003E800000064000000015A70200700000DCE000000080000000200000000000000000000002500000000libArcus-3.2.20/examples/example.cpp#include <vector> #include <iostream> #include <thread> #include "../src/Socket.h" #include "../src/SocketListener.h" #include "../src/Error.h" #include "example.pb.h" struct Object { public: int id; std::string vertices; std::string normals; std::string indices; }; class Listener : public Arcus::SocketListener { public: void stateChanged(Arcus::SocketState::SocketState new_state) { std::cout << "State Changed: " << new_state << std::endl; } void messageReceived() { } void error(const Arcus::Error& new_error) { std::cout << new_error << std::endl; } }; std::vector<Object> objects; void handleMessage(Arcus::Socket& socket, Arcus::MessagePtr message); int main(int argc, char** argv) { Arcus::Socket socket; socket.registerMessageType(&Example::ObjectList::default_instance()); socket.registerMessageType(&Example::ProgressUpdate::default_instance()); socket.registerMessageType(&Example::SlicedObjectList::default_instance()); socket.addListener(new Listener()); std::cout << "Connecting to server\n"; socket.connect("127.0.0.1", 56789); while(socket.getState() != Arcus::SocketState::Connected) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::cout << "Connected to server\n"; while(true) { if(socket.getState() == Arcus::SocketState::Connected) { auto message = socket.takeNextMessage(); if(message) { handleMessage(socket, message); } std::this_thread::sleep_for(std::chrono::milliseconds(250)); } else if(socket.getState() == Arcus::SocketState::Closed || socket.getState() == Arcus::SocketState::Error) { break; } } socket.close(); return 0; } void handleMessage(Arcus::Socket& socket, Arcus::MessagePtr message) { // (Dynamicly) cast the message to one of our types. If this works (does not return a nullptr), we've found the right type. auto objectList = dynamic_cast<Example::ObjectList*>(message.get()); if(objectList) { objects.clear(); std::cout << "Received object list containing " << objectList->objects_size() << " objects" << std::endl; for(auto objectDesc : objectList->objects()) { Object obj; obj.id = objectDesc.id(); obj.vertices = objectDesc.vertices(); obj.normals = objectDesc.normals(); obj.indices = objectDesc.indices(); objects.push_back(obj); } auto msg = std::make_shared<Example::SlicedObjectList>(); int progress = 0; for(auto object : objects) { auto slicedObject = msg->add_objects(); slicedObject->set_id(object.id); for(int i = 0; i < 1000; ++i) { auto polygon = slicedObject->add_polygons(); polygon->set_type(i % 2 == 0 ? Example::Polygon_Type_InnerType : Example::Polygon_Type_OuterType); polygon->set_points(object.vertices); } auto update = std::make_shared<Example::ProgressUpdate>(); update->set_objectid(object.id); update->set_amount((float(++progress) / float(objects.size())) * 100.f); socket.sendMessage(update); } std::cout << "Sending SlicedObjectList" << std::endl; socket.sendMessage(msg); return; } } 07070100833168000081A4000003E800000064000000015A70200700000274000000080000000200000000000000000000002700000000libArcus-3.2.20/examples/example.protosyntax = "proto3"; package Example; message ObjectList { repeated Object objects = 1; } message Object { int32 id = 1; bytes vertices = 2; //An array of 3 floats. bytes normals = 3; //An array of 3 floats. bytes indices = 4; //An array of ints. } message ProgressUpdate { int32 objectId = 1; int32 amount = 2; } message SlicedObjectList { repeated SlicedObject objects = 1; } message SlicedObject { int32 id = 1; repeated Polygon polygons = 2; } message Polygon { enum Type { InnerType = 0; OuterType = 1; } Type type = 1; bytes points = 2; } 0707010083316B000081A4000003E800000064000000015A70200700000927000000080000000200000000000000000000002400000000libArcus-3.2.20/examples/example.pyimport Arcus import time import os.path class Listener(Arcus.SocketListener): def stateChanged(self, state): print("Socket state changed:", state) def messageReceived(self): message = self.getSocket().takeNextMessage() if message.getTypeName() == "Example.ProgressUpdate": print("Progress:", message.amount) if message.getTypeName() == "Example.SlicedObjectList": print("Sliced Objects:", message.repeatedMessageCount("objects")) for i in range(message.repeatedMessageCount("objects")): obj = message.getRepeatedMessage("objects", i) print(" Object ID:", obj.id) print(" Polygon Count:", obj.repeatedMessageCount("polygons")) def error(self, error): print(error) print("Creating socket") socket = Arcus.Socket() print("Registering message types") path = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") if not socket.registerAllMessageTypes(path + "/example.proto"): print("Failed to register messages:", socket.getLastError()) print("Creating listener") listener = Listener() socket.addListener(listener) print("Listening for connections on 127.0.0.1:56789") socket.listen('127.0.0.1', 56789) while(socket.getState() != Arcus.SocketState.Connected): time.sleep(0.1) #time.sleep(5) #Sleep for a bit so the other side can connect if(socket.getState() == Arcus.SocketState.Connected): print("Connection established") else: print(socket.getState()) print("Could not establish a connection:", socket.getLastError()) exit(1) for i in range(10): msg = socket.createMessage("Example.ObjectList") for i in range(100): obj = msg.addRepeatedMessage("objects") obj.id = i obj.vertices = b'abcdefghijklmnopqrstuvwxyz' * 10 obj.normals = b'abcdefghijklmnopqrstuvwxyz' * 10 obj.indices = b'abcdefghijklmnopqrstuvwxyz' * 10 print("Sending message containing", msg.repeatedMessageCount("objects"), "objects") socket.sendMessage(msg) time.sleep(1) if socket.getState() != Arcus.SocketState.Connected: print("Socket lost connection, aborting!") break time.sleep(5) #Sleep for a bit more so we can receive replies to what we just sent. print("Closing connection") socket.close() 07070100833169000081ED000003E800000064000000015A7020070000007C000000080000000200000000000000000000002700000000libArcus-3.2.20/examples/example_py.sh#!/bin/sh PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}:${CMAKE_SOURCE_DIR}/python python3 ${CMAKE_CURRENT_SOURCE_DIR}/example.py 0707010083E172000041ED000003E800000064000000025A70200700000000000000080000000200000000000000000000001700000000libArcus-3.2.20/python07070100833184000081A4000003E800000064000000015A702007000006B7000000080000000200000000000000000000002100000000libArcus-3.2.20/python/Error.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace ErrorCode { enum ErrorCode { UnknownError, CreationError, ConnectFailedError, BindFailedError, AcceptFailedError, SendFailedError, ReceiveFailedError, UnknownMessageTypeError, ParseFailedError, ConnectionResetError, MessageRegistrationFailedError, InvalidStateError, InvalidMessageError, Debug, }; }; class Error { %TypeHeaderCode #include "Error.h" %End public: Error(); Error(ErrorCode::ErrorCode error_code, const std::string& error_message); Error(const Error& error); ErrorCode::ErrorCode getErrorCode() const; std::string getErrorMessage() const; bool isFatalError() const; bool isValid() const; void setFatalError(bool fatal); PyObject* __repr__(); %MethodCode return PyUnicode_FromString(sipCpp->toString().c_str()); %End }; 0707010083317F000081A4000003E800000064000000015A702007000020BD000000080000000200000000000000000000002900000000libArcus-3.2.20/python/PythonMessage.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PythonMessage.h" #include <Python.h> #include <google/protobuf/message.h> #include <google/protobuf/reflection.h> using namespace Arcus; using namespace google::protobuf; PythonMessage::PythonMessage(google::protobuf::Message* message) { _message = message; _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } Arcus::PythonMessage::PythonMessage(const MessagePtr& message) { _shared_message = message; _message = message.get(); _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } PythonMessage::~PythonMessage() { } std::string Arcus::PythonMessage::getTypeName() const { return _message->GetTypeName(); } MessagePtr Arcus::PythonMessage::getSharedMessage() const { return _shared_message; } bool Arcus::PythonMessage::__hasattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); return bool(field); } PyObject* Arcus::PythonMessage::__getattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: return PyFloat_FromDouble(_reflection->GetFloat(*_message, field)); case FieldDescriptor::TYPE_DOUBLE: return PyFloat_FromDouble(_reflection->GetDouble(*_message, field)); case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return PyLong_FromLong(_reflection->GetInt32(*_message, field)); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return PyLong_FromLongLong(_reflection->GetInt64(*_message, field)); case FieldDescriptor::TYPE_UINT32: return PyLong_FromUnsignedLong(_reflection->GetUInt32(*_message, field)); case FieldDescriptor::TYPE_UINT64: return PyLong_FromUnsignedLongLong(_reflection->GetUInt64(*_message, field)); case FieldDescriptor::TYPE_BOOL: if(_reflection->GetBool(*_message, field)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } case FieldDescriptor::TYPE_BYTES: { std::string data = _reflection->GetString(*_message, field); return PyBytes_FromStringAndSize(data.c_str(), data.size()); } case FieldDescriptor::TYPE_STRING: return PyUnicode_FromString(_reflection->GetString(*_message, field).c_str()); case FieldDescriptor::TYPE_ENUM: return PyLong_FromLong(_reflection->GetEnumValue(*_message, field)); default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); return nullptr; } } void Arcus::PythonMessage::__setattr__(const std::string& field_name, PyObject* value) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: _reflection->SetFloat(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_DOUBLE: _reflection->SetDouble(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SFIXED32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: _reflection->SetInt32(_message, field, PyLong_AsLong(value)); break; case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: _reflection->SetInt64(_message, field, PyLong_AsLongLong(value)); break; case FieldDescriptor::TYPE_UINT32: _reflection->SetUInt32(_message, field, PyLong_AsUnsignedLong(value)); break; case FieldDescriptor::TYPE_UINT64: _reflection->SetUInt64(_message, field, PyLong_AsUnsignedLongLong(value)); break; case FieldDescriptor::TYPE_BOOL: if(value == Py_True) { _reflection->SetBool(_message, field, true); } else { _reflection->SetBool(_message, field, false); } break; case FieldDescriptor::TYPE_BYTES: { Py_buffer buffer; PyObject_GetBuffer(value, &buffer, PyBUF_SIMPLE); std::string str(reinterpret_cast<char*>(buffer.buf), buffer.len); _reflection->SetString(_message, field, str); break; } case FieldDescriptor::TYPE_STRING: _reflection->SetString(_message, field, PyUnicode_AsUTF8(value)); break; case FieldDescriptor::TYPE_ENUM: { if(PyUnicode_Check(value)) { auto enum_value = _descriptor->FindEnumValueByName(PyUnicode_AsUTF8(value)); _reflection->SetEnum(_message, field, enum_value); } else { _reflection->SetEnumValue(_message, field, PyLong_AsLong(value)); } break; } default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); break; } } PythonMessage* Arcus::PythonMessage::addRepeatedMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } Message* message = _reflection->AddMessage(_message, field); return new PythonMessage(message); } int PythonMessage::repeatedMessageCount(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return -1; } return _reflection->FieldSize(*_message, field); } PythonMessage* Arcus::PythonMessage::getMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableMessage(_message, field)); } PythonMessage* Arcus::PythonMessage::getRepeatedMessage(const std::string& field_name, int index) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } if(index < 0 || index > _reflection->FieldSize(*_message, field)) { PyErr_SetString(PyExc_IndexError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableRepeatedMessage(_message, field, index)); } int Arcus::PythonMessage::getEnumValue(const std::string& enum_value) const { auto field = _descriptor->FindEnumValueByName(enum_value); if(!field) { return -1; } return field->number(); } 07070100833181000081A4000003E800000064000000015A70200700001058000000080000000200000000000000000000002700000000libArcus-3.2.20/python/PythonMessage.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_PYTHON_MESSAGE_H #define ARCUS_PYTHON_MESSAGE_H #include <Python.h> #include "Types.h" namespace google { namespace protobuf { class Descriptor; class Reflection; } } namespace Arcus { /** * A simple wrapper around a Protobuf message so it can be used from Python. * * This class wraps a Protobuf message and makes it possible to get and set * values from the message. Message properties are exposed as Python properties * so can be set using things like `message.data = b"something"` from Python. * * Repeated messages are supported, using addRepeatedMessage, repeatedMessageCount * and getRepeatedMessage. A repeated message is returned as a PythonMessage object * so exposes the same API as the top level message. */ class PythonMessage { public: PythonMessage(google::protobuf::Message* message); PythonMessage(const MessagePtr& message); virtual ~PythonMessage(); /** * Get the message type name of this message. */ std::string getTypeName() const; /** * Python property interface. */ bool __hasattr__(const std::string& field_name) const; PyObject* __getattr__(const std::string& field_name) const; void __setattr__(const std::string& name, PyObject* value); /** * Add an instance of a Repeated Message to a specific field. * * \param field_name The name of the field to add a message to. * * \return A pointer to an instance of PythonMessage wrapping the new Message in the field. */ PythonMessage* addRepeatedMessage(const std::string& field_name); /** * Get the number of messages in a repeated message field. */ int repeatedMessageCount(const std::string& field_name) const; /** * Get a specific instance of a message in a repeated message field. * * \param field_name The name of a repeated message field to get an instance from. * \param index The index of the item to get in the repeated field. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getRepeatedMessage(const std::string& field_name, int index); /** * Get a specific instance of a message in a message field. * * \param field_name The name of a repeated message field to get an instance from. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getMessage(const std::string& field_name); /** * Get the value of a certain enumeration. * * \param enum_value The fully-qualified name of an Enum value. * * \return The integer value of the specified enum. */ int getEnumValue(const std::string& enum_value) const; /** * Internal. */ MessagePtr getSharedMessage() const; private: MessagePtr _shared_message; google::protobuf::Message* _message; const google::protobuf::Reflection* _reflection; const google::protobuf::Descriptor* _descriptor; }; } #endif //ARCUS_MESSAGE_PTR_H 0707010083317E000081A4000003E800000064000000015A70200700000706000000080000000200000000000000000000002900000000libArcus-3.2.20/python/PythonMessage.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ class PythonMessage { %TypeHeaderCode #include "PythonMessage.h" %End public: virtual ~PythonMessage(); std::string getTypeName() const; bool __hasattr__(const std::string&) const /AllowNone/; PyObject* __getattr__(const std::string&) const /AllowNone, HoldGIL/; void __setattr__(const std::string&, PyObject*) /AllowNone/; %MethodCode sipCpp->__setattr__(*a0, a1); %End void __delattr__(const std::string&); %MethodCode PyErr_SetString(PyExc_NotImplementedError, "__delattr__ not supported on messages."); return 0; %End PythonMessage* addRepeatedMessage(const std::string& field_name) /TransferBack/; int repeatedMessageCount(const std::string& field_name) const; PythonMessage* getRepeatedMessage(const std::string& field_name, int index) /TransferBack/; PythonMessage* getMessage(const std::string& field_name) /TransferBack/; int getEnumValue(const std::string& enum_value) const; private: PythonMessage(); }; 07070100833182000081A4000003E800000064000000015A702007000006E4000000080000000200000000000000000000002200000000libArcus-3.2.20/python/Socket.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ %Module(name = Arcus, call_super_init = True) %Include Types.sip %Include SocketListener.sip %Include PythonMessage.sip %Include Error.sip %ModuleHeaderCode using namespace Arcus; %End class Socket { %TypeHeaderCode #include "Socket.h" %End public: Socket(); virtual ~Socket(); SocketState::SocketState getState() const; Error getLastError() const; void clearError(); void addListener(SocketListener* listener /TransferThis/); void removeListener(SocketListener* listener); void connect(const std::string& address, int port); void listen(const std::string& address, int port); void close() /ReleaseGIL/; void reset() /ReleaseGIL/; void sendMessage(MessagePtr message); MessagePtr takeNextMessage(); MessagePtr createMessage(const std::string& type_name); bool registerAllMessageTypes(const std::string& file_name); private: Socket(const Socket&); Socket& operator=(const Socket&); }; 07070100833180000081A4000003E800000064000000015A70200700000480000000080000000200000000000000000000002A00000000libArcus-3.2.20/python/SocketListener.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ class SocketListener { %TypeHeaderCode #include "SocketListener.h" %End public: SocketListener(); virtual ~SocketListener(); Socket* getSocket(); virtual void stateChanged(SocketState::SocketState newState) = 0 /HoldGIL/; virtual void messageReceived() = 0 /HoldGIL/; virtual void error(const Error& error) = 0 /HoldGIL/; }; 07070100833183000081A4000003E800000064000000015A70200700000ED7000000080000000200000000000000000000002100000000libArcus-3.2.20/python/Types.sip/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Convert a python str object to a std::string. %MappedType std::string { %TypeHeaderCode #include <string> %End %ConvertFromTypeCode // convert an std::string to a Python (unicode) string PyObject* newstring; newstring = PyUnicode_DecodeUTF8(sipCpp->c_str(), sipCpp->length(), NULL); if(newstring == NULL) { PyErr_Clear(); newstring = PyBytes_FromString(sipCpp->c_str()); } return newstring; %End %ConvertToTypeCode // Allow a Python string (or a unicode string) whenever a string is // expected. // If argument is a Unicode string, just decode it to UTF-8 // If argument is a Python string, assume it's UTF-8 if (sipIsErr == NULL) return (PyBytes_Check(sipPy) || PyUnicode_Check(sipPy)); if (sipPy == Py_None) { *sipCppPtr = new std::string; return 1; } if (PyUnicode_Check(sipPy)) { PyObject* s = PyUnicode_AsEncodedString(sipPy, "UTF-8", ""); *sipCppPtr = new std::string(PyBytes_AS_STRING(s)); Py_DECREF(s); return 1; } if (PyBytes_Check(sipPy)) { *sipCppPtr = new std::string(PyBytes_AS_STRING(sipPy)); return 1; } return 0; %End }; // Convert a MessagePtr (aka std::shared_ptr<google::protobuf::Message>) to a PythonMessage* %MappedType MessagePtr { %TypeHeaderCode #include <memory> #include "PythonMessage.h" %End %ConvertFromTypeCode // Convert a Protobuf message to a Python object if(!(*sipCpp)) { PyErr_SetString(PyExc_ValueError, "Unknown message type"); return NULL; } const sipTypeDef* message_type = sipFindType("PythonMessage"); PythonMessage* message = new PythonMessage(*sipCpp); sipTransferObj = Py_None; PyObject* msg = sipConvertFromType(message, message_type, sipTransferObj); if(!msg) { delete message; return NULL; } return msg; %End %ConvertToTypeCode // Convert a Python object to a Protobuf message const sipTypeDef* message_type = sipFindType("PythonMessage"); if(sipIsErr == NULL) { return sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE); } if(sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE)) { int iserr = 0; int state = 0; PythonMessage* message = reinterpret_cast<PythonMessage*>(sipConvertToType(sipPy, message_type, NULL, 0, &state, &iserr)); if(iserr != 0) { PyErr_SetString(PyExc_ValueError, "Could not convert to Message"); return 0; } MessagePtr msg = message->getSharedMessage(); *sipCppPtr = new MessagePtr(msg); sipReleaseType(message, message_type, state); } return sipGetState(sipTransferObj); %End }; %UnitCode #include "Types.h" %End namespace SocketState { enum SocketState { Initial, Connecting, Connected, Opening, Listening, Closing, Closed, Error }; }; 0707010083E171000041ED000003E800000064000000025A70200700000000000000080000000200000000000000000000001400000000libArcus-3.2.20/src0707010083317A000081A4000003E800000064000000015A702007000000E7000000080000000200000000000000000000002200000000libArcus-3.2.20/src/ArcusExport.h#ifndef ARCUS_EXPORT_H #define ARCUS_EXPORT_H #if _WIN32 #ifdef MAKE_ARCUS_LIB #define ARCUS_EXPORT __declspec(dllexport) #else #define ARCUS_EXPORT #endif #else #define ARCUS_EXPORT #endif #endif 07070100833174000081A4000003E800000064000000015A70200700000978000000080000000200000000000000000000001E00000000libArcus-3.2.20/src/Error.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Error.h" #include <iostream> using namespace Arcus; Arcus::Error::Error() : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { } Arcus::Error::Error(ErrorCode::ErrorCode error_code, const std::string& error_message) : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { _error_code = error_code; _error_message = error_message; } ErrorCode::ErrorCode Arcus::Error::getErrorCode() const { return _error_code; } std::string Arcus::Error::getErrorMessage() const { return _error_message; } bool Arcus::Error::isFatalError() const { return _fatal_error; } bool Arcus::Error::isValid() const { return _error_code != ErrorCode::UnknownError || !_error_message.empty(); } int Arcus::Error::getNativeErrorCode() const { return _native_error_code; } void Arcus::Error::setFatalError(bool fatal) { _fatal_error = fatal; } void Arcus::Error::setNativeErrorCode(int code) { _native_error_code = code; } std::string Arcus::Error::toString() const { static std::string error_start("Arcus Error ("); static std::string fatal_error_start("Arcus Fatal Error ("); static std::string native_prefix(", native "); static std::string message_separator("): "); return (_fatal_error ? fatal_error_start : error_start) + std::to_string(static_cast<int>(_error_code)) + (_native_error_code != 0 ? native_prefix + std::to_string(_native_error_code) : "") + message_separator + _error_message; } std::ostream & operator<<(std::ostream& stream, const Arcus::Error& error) { return stream << error.toString(); } 07070100833171000081A4000003E800000064000000015A70200700000E33000000080000000200000000000000000000001C00000000libArcus-3.2.20/src/Error.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_ERROR_H #define ARCUS_ERROR_H #include "ArcusExport.h" #include "Types.h" namespace Arcus { /** * Possible error codes. */ namespace ErrorCode { // Note: Not using enum class due to incompatibility with SIP. enum ErrorCode { UnknownError, ///< An unknown error occurred. CreationError, ///< Socket creation failed. ConnectFailedError, ///< Connection failed. BindFailedError, ///< Bind to IP and port failed. AcceptFailedError, ///< Accepting an incoming connection failed. SendFailedError, ///< Sending a message failed. ReceiveFailedError, ///< Receiving a message failed. UnknownMessageTypeError, ///< Received a message with an unknown message type. ParseFailedError, ///< Parsing the received message failed. ConnectionResetError, ///< The connection was reset by peer. MessageRegistrationFailedError, ///< Message registration failed. InvalidStateError, ///< Socket is in an invalid state. InvalidMessageError, ///< Message being handled is a nullptr or otherwise invalid. Debug, //Debug messages }; } /** * A class representing an error with an error code and an error message. */ class ARCUS_EXPORT Error { public: /** * Default constructor. */ Error(); /** * Create an error with an error code and error message. */ Error(ErrorCode::ErrorCode error_code, const std::string& error_message); /** * Get the error code of this error. */ ErrorCode::ErrorCode getErrorCode() const; /** * Get the error message. */ std::string getErrorMessage() const; /** * Is this error considered a fatal error? */ bool isFatalError() const; /** * Is this error valid? */ bool isValid() const; /** * The error code as reported by the platform. */ int getNativeErrorCode() const; /** * Set whether this should be considered a fatal error. */ void setFatalError(bool fatal); /** * Set the native error code, if any. */ void setNativeErrorCode(int code); /** * Convert the error to a string that can be printed. */ std::string toString() const; private: ErrorCode::ErrorCode _error_code; std::string _error_message; bool _fatal_error; int _native_error_code; }; } // Output the error to a stream. ARCUS_EXPORT std::ostream& operator<<(std::ostream& stream, const Arcus::Error& error); #endif //ARCUS_ERROR_H 0707010083316F000081A4000003E800000064000000015A7020070000175C000000080000000200000000000000000000002900000000libArcus-3.2.20/src/MessageTypeStore.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "MessageTypeStore.h" #include <unordered_map> #include <sstream> #include <iostream> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/compiler/importer.h> using namespace Arcus; /** * Taken from libstdc++, this implements hashing a string to an int. * * Since we rely on the hashing method for type ID generation and the implementation * of std::hash differs between compilers, we need to make sure we use the same * implementation everywhere. */ uint32_t hash(const std::string& input) { const char* data = input.c_str(); uint32_t length = input.size(); uint32_t result = static_cast<uint32_t>(2166136261UL); for(; length; --length) { result ^= static_cast<uint32_t>(*data++); result *= static_cast<uint32_t>(16777619UL); } return result; } class ErrorCollector : public google::protobuf::compiler::MultiFileErrorCollector { public: ErrorCollector() : _error_count(0) { } void AddError(const std::string& filename, int line, int column, const std::string& message) override { _stream << "[" << filename << " (" << line << "," << column << ")] " << message << std::endl; _error_count++; } std::string getAllErrors() { return _stream.str(); } int getErrorCount() { return _error_count; } private: std::stringstream _stream; int _error_count; }; class MessageTypeStore::Private { public: std::unordered_map<uint, const google::protobuf::Message*> message_types; std::unordered_map<const google::protobuf::Descriptor*, uint> message_type_mapping; std::shared_ptr<ErrorCollector> error_collector; std::shared_ptr<google::protobuf::compiler::DiskSourceTree> source_tree; std::shared_ptr<google::protobuf::compiler::Importer> importer; std::shared_ptr<google::protobuf::DynamicMessageFactory> message_factory; }; Arcus::MessageTypeStore::MessageTypeStore() : d(new Private) { } Arcus::MessageTypeStore::~MessageTypeStore() { } bool Arcus::MessageTypeStore::hasType(uint32_t type_id) const { if(d->message_types.find(type_id) != d->message_types.end()) { return true; } return false; } bool Arcus::MessageTypeStore::hasType(const std::string& type_name) const { uint32_t type_id = hash(type_name); return hasType(type_id); } MessagePtr Arcus::MessageTypeStore::createMessage(uint32_t type_id) const { if(!hasType(type_id)) { return MessagePtr(); } return MessagePtr(d->message_types[type_id]->New()); } MessagePtr Arcus::MessageTypeStore::createMessage(const std::string& type_name) const { uint32_t type_id = hash(type_name); return createMessage(type_id); } uint32_t Arcus::MessageTypeStore::getMessageTypeId(const MessagePtr& message) { return hash(message->GetTypeName()); } std::string Arcus::MessageTypeStore::getErrorMessages() const { return d->error_collector->getAllErrors(); } bool Arcus::MessageTypeStore::registerMessageType(const google::protobuf::Message* message_type) { uint32_t type_id = hash(message_type->GetTypeName()); if(hasType(type_id)) { return false; } d->message_types[type_id] = message_type; d->message_type_mapping[message_type->GetDescriptor()] = type_id; return true; } bool Arcus::MessageTypeStore::registerAllMessageTypes(const std::string& file_name) { if(!d->importer) { d->error_collector = std::make_shared<ErrorCollector>(); d->source_tree = std::make_shared<google::protobuf::compiler::DiskSourceTree>(); #ifndef _WIN32 d->source_tree->MapPath("/", "/"); #else // Because of silly DiskSourceTree, we need to make sure absolute paths to // the protocol file are properly mapped. for(auto letter : std::string("abcdefghijklmnopqrstuvwxyz")) { std::string lc(1, letter); std::string uc(1, toupper(letter)); d->source_tree->MapPath(lc + ":/", lc + ":\\"); d->source_tree->MapPath(uc + ":/", uc + ":\\"); } #endif d->importer = std::make_shared<google::protobuf::compiler::Importer>(d->source_tree.get(), d->error_collector.get()); } auto descriptor = d->importer->Import(file_name); if(d->error_collector->getErrorCount() > 0) { return false; } if(!d->message_factory) { d->message_factory = std::make_shared<google::protobuf::DynamicMessageFactory>(); } for(int i = 0; i < descriptor->message_type_count(); ++i) { auto message_type_descriptor = descriptor->message_type(i); auto message_type = d->message_factory->GetPrototype(message_type_descriptor); uint32_t type_id = hash(message_type->GetTypeName()); d->message_types[type_id] = message_type; d->message_type_mapping[message_type_descriptor] = type_id; } return true; } void Arcus::MessageTypeStore::dumpMessageTypes() { for(auto type : d->message_types) { std::cout << "Type ID: " << type.first << " Type Name: " << type.second->GetTypeName() << std::endl; } } 07070100833177000081A4000003E800000064000000015A70200700000E2D000000080000000200000000000000000000002700000000libArcus-3.2.20/src/MessageTypeStore.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_MESSAGE_TYPE_STORE_H #define ARCUS_MESSAGE_TYPE_STORE_H #include <memory> #include "Types.h" namespace Arcus { /** * A class to manage the different types of messages that are available. */ class MessageTypeStore { public: MessageTypeStore(); ~MessageTypeStore(); /** * Check if a certain message type was registered. * * \param type_id The ID of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(uint32_t type_id) const; /** * Check if a certain message type was registered. * * \param type_name The name of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(const std::string& type_name) const; /** * Create a Message instance of a certain type. * * \param type_id The type ID of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(uint32_t type_id) const; /** * Create a Message instance of a certain type. * * \param type_name The name of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(const std::string& type_name) const; /** * Get the type ID of a message. * * \param message The message to get the type ID of. * * \return The type id of the message. */ uint32_t getMessageTypeId(const MessagePtr& message); std::string getErrorMessages() const; /** * Register a message type. * * \param message_type An instance of a message that will be used as factory to create new messages. * * \return true if registration was successful, false if not. */ bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types from a Protobuf protocol description file. * * \param file_name The absolute path to a Protobuf proto file. * * \return true if registration was successful, false if not. */ bool registerAllMessageTypes(const std::string& file_name); /** * Dump all message type IDs and type names to stdout. */ void dumpMessageTypes(); private: class Private; const std::unique_ptr<Private> d; }; } #endif //ARCUS_MESSAGE_TYPE_STORE_H 07070100833175000081A4000003E800000064000000015A7020070000197B000000080000000200000000000000000000002700000000libArcus-3.2.20/src/PlatformSocket.cpp/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PlatformSocket_p.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #include <errno.h> #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0x0 //Don't request NOSIGNAL on systems where this is not implemented. #endif #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0x0 #endif using namespace Arcus::Private; #ifdef _WIN32 void initializeWSA() { static bool wsaInitialized = false; if(!wsaInitialized) { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); wsaInitialized = true; } } #endif // Create a sockaddr_in structure from an address and port. sockaddr_in createAddress(const std::string& address, int port) { sockaddr_in a; a.sin_family = AF_INET; #ifdef _WIN32 InetPton(AF_INET, address.c_str(), &(a.sin_addr)); //Note: Vista and higher only. #else ::inet_pton(AF_INET, address.c_str(), &(a.sin_addr)); #endif a.sin_port = htons(port); return a; } Arcus::Private::PlatformSocket::PlatformSocket() { #ifdef _WIN32 initializeWSA(); #endif } Arcus::Private::PlatformSocket::~PlatformSocket() { } bool Arcus::Private::PlatformSocket::create() { _socket_id = ::socket(AF_INET, SOCK_STREAM, 0); return _socket_id != -1; } bool Arcus::Private::PlatformSocket::connect(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::connect(_socket_id, reinterpret_cast<sockaddr*>(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::bind(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::bind(_socket_id, reinterpret_cast<sockaddr*>(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::listen(int backlog) { int result = ::listen(_socket_id, backlog); return result == 0; } bool Arcus::Private::PlatformSocket::accept() { int new_socket = ::accept(_socket_id, 0, 0); #ifdef _WIN32 ::closesocket(_socket_id); #else ::close(_socket_id); #endif if(new_socket == -1) { return false; } else { _socket_id = new_socket; return true; } } bool Arcus::Private::PlatformSocket::close() { int result = 0; #ifdef _WIN32 result = ::closesocket(_socket_id); #else result = ::close(_socket_id); #endif return result == 0; } bool Arcus::Private::PlatformSocket::shutdown(PlatformSocket::ShutdownDirection direction) { int flag = 0; switch(direction) { case ShutdownDirection::ShutdownRead: #ifdef _WIN32 flag = SD_RECEIVE; #else flag = SHUT_RD; #endif break; case ShutdownDirection::ShutdownWrite: #ifdef _WIN32 flag = SD_SEND; #else flag = SHUT_WR; #endif break; case ShutdownDirection::ShutdownBoth: #ifdef _WIN32 flag = SD_BOTH; #else flag = SHUT_RDWR; #endif } return (::shutdown(_socket_id, flag) == 0); } void Arcus::Private::PlatformSocket::flush() { char* buffer = new char[256]; socket_size num = 0; while(num > 0) { num = ::recv(_socket_id, buffer, 256, MSG_DONTWAIT); } } socket_size Arcus::Private::PlatformSocket::writeUInt32(uint32_t data) { uint32_t temp = htonl(data); socket_size sent_size = ::send(_socket_id, reinterpret_cast<const char*>(&temp), 4, MSG_NOSIGNAL); return sent_size; } socket_size Arcus::Private::PlatformSocket::writeBytes(std::size_t size, const char* data) { return ::send(_socket_id, data, size, MSG_NOSIGNAL); } socket_size Arcus::Private::PlatformSocket::readUInt32(uint32_t* output) { #ifndef _WIN32 errno = 0; #endif uint32_t buffer; socket_size num = ::recv(_socket_id, reinterpret_cast<char*>(&buffer), 4, 0); if(num != 4) { #ifdef _WIN32 if(num == WSAETIMEDOUT) { return 0; } else if(WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(errno == EAGAIN) { return 0; } #endif return -1; } *output = ntohl(buffer); return num; } socket_size Arcus::Private::PlatformSocket::readBytes(std::size_t size, char* output) { #ifndef _WIN32 errno = 0; #endif socket_size num = ::recv(_socket_id, output, size, 0); #ifdef _WIN32 if(num == SOCKET_ERROR && WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(num <= 0 && errno == EAGAIN) { return 0; } #endif return num; } bool Arcus::Private::PlatformSocket::setReceiveTimeout(int timeout) { int result = 0; #ifdef _WIN32 result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeout), sizeof(timeout)); return result != SOCKET_ERROR; #else timeval t; t.tv_sec = 0; t.tv_usec = timeout * 1000; result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&t), sizeof(t)); return result == 0; #endif } int Arcus::Private::PlatformSocket::getNativeErrorCode() { #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif } 07070100833178000081A4000003E800000064000000015A702007000019A8000000080000000200000000000000000000002700000000libArcus-3.2.20/src/PlatformSocket_p.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_PLATFORM_SOCKET_P_H #define ARCUS_PLATFORM_SOCKET_P_H #include <memory> #include <string> namespace Arcus { namespace Private { #ifdef _WIN32 typedef int socket_size; #else typedef ssize_t socket_size; #endif /** * Private class that wraps the platform C API for dealing with Sockets. */ class PlatformSocket { public: /** * Which connection direction should be shutdown? */ enum class ShutdownDirection { ShutdownRead, ///< Shutdown reads from the connection. ShutdownWrite, ///< Shutdown writes to the connection. ShutdownBoth, ///< Shutdown the connection both ways. }; PlatformSocket(); ~PlatformSocket(); /** * Create the socket. * * \return true if socket creation was successful, false if not. */ bool create(); /** * Connect to an IP address and port. * * \param address The IP address to connect to. * \param port The port to bind to. * * \return true if the connection was successful, false if not. */ bool connect(const std::string& address, int port); /** * Bind the socket to an address and port. * * \param address The IP address to bind to. * \param port The port to bind to. * * \return true if successful, false if not. */ bool bind(const std::string& address, int port); /** * Mark the socket as listening for new connections. * * \param backlog The amount of queued connections to accept. * * \return true if successful, false if not. */ bool listen(int backlog); /** * Accept the waiting incoming connection and use it as connected socket. * * \return true if successful, false if not. * * \note This call will block until there is a connection waiting to be accepted. */ bool accept(); /** * Close the socket. * * \return true if successful, false if not. */ bool close(); /** * Shutdown the socket. * * \param direction The direction to shutdown. * * \return true if successful, false if not. */ bool shutdown(ShutdownDirection direction); /** * Flush all waiting data and discard it. * * This is mostly intended as an error recovery mechanism, if we detect a failure * in the messages sent over the wire, we can no longer be sure about the rest of * the data on the wire. So rather than trying to figure out if there is an actual * message hidden somewhere, just flush all data so we start with a clean slate. */ void flush(); /** * Write an unsigned 32-bit integer to the socket. * * \param data The integer to write. Will be converted from local endianness to network endianness. * * \return The amount of bytes written (4) or -1 if an error occurred. */ socket_size writeUInt32(uint32_t data); /** * Write data to the the socket. * * \param size The amount of data to write. * \param data A pointer to the data to send. * * \return The amount of bytes written, or -1 if an error occurred. */ socket_size writeBytes(std::size_t size, const char* data); /** * Read an unsigned 32-bit integer from the socket. * * \param output A pointer to an integer that will be written to. * * \return The amount of bytes read (4) or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than 4. */ socket_size readUInt32(uint32_t* output); /** * Read an amount of bytes from the socket. * * \param size The amount of bytes to read. * \param output A pointer to a block of data that can be written to. * * \return The amount of bytes read or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than size. */ socket_size readBytes(std::size_t size, char* output); /** * Set the timeout for the read-related methods. * * The readInt32 and readBytes methods will block for a certain amount of time when * there is not enough data available. This call will set the maximum amount of time these * calls will block. * * \param timeout The amount of time in milliseconds to wait for data. */ bool setReceiveTimeout(int timeout); /** * Return the last error code as reported by the underlying platform. */ int getNativeErrorCode(); private: int _socket_id; }; } } #endif //ARCUS_PLATFORM_SOCKET_P_H 0707010083317C000081A4000003E800000064000000015A70200700001777000000080000000200000000000000000000001F00000000libArcus-3.2.20/src/Socket.cpp/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Socket.h" #include "Socket_p.h" #include <algorithm> using namespace Arcus; Socket::Socket() : d(new Private) { } Socket::~Socket() { if(d->thread) { if(d->state != SocketState::Closed || d->state != SocketState::Error) { close(); } delete d->thread; } for(auto listener : d->listeners) { delete listener; } } SocketState::SocketState Socket::getState() const { return d->state; } Error Socket::getLastError() const { return d->last_error; } void Socket::clearError() { d->last_error = Error(); } bool Socket::registerMessageType(const google::protobuf::Message* message_type) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return false; } return d->message_types.registerMessageType(message_type); } bool Socket::registerAllMessageTypes(const std::string& file_name) { if(file_name.empty()) { d->error(ErrorCode::MessageRegistrationFailedError, "Empty file name"); return false; } if(d->state != SocketState::Initial) { d->error(ErrorCode::MessageRegistrationFailedError, "Socket is not in initial state"); return false; } if(!d->message_types.registerAllMessageTypes(file_name)) { d->error(ErrorCode::MessageRegistrationFailedError, d->message_types.getErrorMessages()); return false; } return true; } void Socket::addListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } listener->setSocket(this); d->listeners.push_back(listener); } void Socket::removeListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } auto itr = std::find(d->listeners.begin(), d->listeners.end(), listener); d->listeners.erase(itr); } void Socket::connect(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Connecting; } void Socket::reset() { if (d->state != SocketState::Closed && d->state != SocketState::Error) { d->error(ErrorCode::InvalidStateError, "Socket is not in closed or error state"); return; } if(d->thread) { d->thread->join(); d->thread = nullptr; } d->state = SocketState::Initial; d->next_state = SocketState::Initial; clearError(); } void Socket::listen(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Opening; } void Socket::close() { if(d->state == SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Cannot close a socket in initial state"); return; } if(d->state == SocketState::Closed || d->state == SocketState::Error) { // Silently ignore this, as calling close on an already closed socket should be fine. return; } if(d->state == SocketState::Connected) { // Make the socket request close. d->next_state = SocketState::Closing; // Wait with closing until we properly clear the send queue. while(d->state == SocketState::Closing) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } else { // We are still in an unconnected state but want to abort any connection // attempt. So disable any communication on the socket to make sure calls // like accept() exit, then close the socket. d->platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownBoth); d->platform_socket.close(); d->next_state = SocketState::Closed; } if(d->thread) { d->thread->join(); delete d->thread; d->thread = nullptr; } } void Socket::sendMessage(MessagePtr message) { if(!message) { d->error(ErrorCode::InvalidMessageError, "Message cannot be nullptr"); return; } std::lock_guard<std::mutex> lock(d->sendQueueMutex); d->sendQueue.push_back(message); } MessagePtr Socket::takeNextMessage() { std::lock_guard<std::mutex> lock(d->receiveQueueMutex); if(d->receiveQueue.size() > 0) { MessagePtr next = d->receiveQueue.front(); d->receiveQueue.pop_front(); return next; } else { return nullptr; } } MessagePtr Arcus::Socket::createMessage(const std::string& type) { return d->message_types.createMessage(type); } 07070100833176000081A4000003E800000064000000015A702007000011E5000000080000000200000000000000000000001D00000000libArcus-3.2.20/src/Socket.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_SOCKET_H #define ARCUS_SOCKET_H #include <memory> #include "Types.h" #include "Error.h" #include "ArcusExport.h" namespace Arcus { class SocketListener; /** * \brief Threaded socket class. * * This class represents a socket and the logic for parsing and handling * protobuf messages that can be sent and received over this socket. * * Please see the README in libArcus for more details. */ class ARCUS_EXPORT Socket { public: Socket(); virtual ~Socket(); /** * Get the socket state. * * \return The current socket state. */ SocketState::SocketState getState() const; /** * Get the last error. * * \return The last error that occurred. */ Error getLastError() const; /** * Clear any error that was set previously. */ void clearError(); /** * Register a new type of Message to handle. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param message_type An instance of the Message that will be used as factory object. * */ bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types contained in a Protobuf protocol description file. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param file_name The absolute path to a Protobuf protocol file to load message types from. */ bool registerAllMessageTypes(const std::string& file_name); /** * Add a listener object that will be notified of socket events. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to add. */ void addListener(SocketListener* listener); /** * Remove a listener from the list of listeners. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to remove. */ void removeListener(SocketListener* listener); /** * Connect to an address and port. * * \param address The IP address to connect to. * \param port The port to connect to. */ void connect(const std::string& address, int port); /** * Listen for connections on an address and port. * * \param address The IP address to listen on. * \param port The port to listen on. */ void listen(const std::string& address, int port); /** * Close the connection and stop handling any messages. */ void close(); /** * Reset a socket for re-use. State must be Closed or Error */ void reset(); /** * Send a message across the socket. */ void sendMessage(MessagePtr message); /** * Remove and return the next pending message from the queue. */ MessagePtr takeNextMessage(); /** * Create an instance of a Message class. * * \param type_name The type name of the Message type to create an instance of. */ MessagePtr createMessage(const std::string& type_name); private: // Copy and assignment is not supported. Socket(const Socket&); Socket& operator=(const Socket& other); class Private; const std::unique_ptr<Private> d; }; } #endif // ARCUS_SOCKET_H 07070100833173000081A4000003E800000064000000015A702007000003EA000000080000000200000000000000000000002700000000libArcus-3.2.20/src/SocketListener.cpp/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SocketListener.h" #include "Socket.h" using namespace Arcus; Socket* SocketListener::getSocket() const { return _socket; } void SocketListener::setSocket(Socket* socket) { _socket = socket; } 0707010083317B000081A4000003E800000064000000015A70200700000B97000000080000000200000000000000000000002500000000libArcus-3.2.20/src/SocketListener.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_SOCKETLISTENER_H #define ARCUS_SOCKETLISTENER_H #include "Types.h" #include "ArcusExport.h" namespace Arcus { class Socket; class Error; /** * Interface for socket event listeners. * * This interface should be implemented to receive notifications when * certain events occur on the socket. The methods of this interface * are called from the Socket's worker thread and thus with that thread * as current thread. This interface is thus primarily intended as an * abstraction to implement your own thread synchronisation. * * For example, when using the Qt event loop, you could emit a queued * signal from a subclass of this class, to make sure the actual event * is handled on the main thread. */ class ARCUS_EXPORT SocketListener { public: SocketListener() : _socket(nullptr) { } virtual ~SocketListener() { } /** * \return The socket this listener is listening to. */ Socket* getSocket() const; /** * Called whenever the socket's state changes. * * \param newState The new state of the socket. */ virtual void stateChanged(SocketState::SocketState newState) = 0; /** * Called whenever a new message has been received and * correctly parsed. * * \note This is explicitly not passed the received message. Instead, it is put * on a receive queue so other threads can take care of it. */ virtual void messageReceived() = 0; /** * Called whenever an error occurs on the socket. * * \param errorMessage The error message. */ virtual void error(const Error& error) = 0; private: // So we can call setSocket from Socket without making it public interface. friend class Socket; // Set the socket this listener is listening to. // This is automatically called by the socket when Socket::addListener() is called. void setSocket(Socket* socket); Socket* _socket; }; } #endif // ARCUS_SOCKETLISTENER_H 07070100833179000081A4000003E800000064000000015A70200700004E91000000080000000200000000000000000000001F00000000libArcus-3.2.20/src/Socket_p.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <thread> #include <mutex> #include <string> #include <list> #include <unordered_map> #include <deque> #include <iostream> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <signal.h> #endif #include <google/protobuf/message.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/io/coded_stream.h> #include "Socket.h" #include "Types.h" #include "SocketListener.h" #include "MessageTypeStore.h" #include "Error.h" #include "WireMessage_p.h" #include "PlatformSocket_p.h" #define VERSION_MAJOR 1 #define VERSION_MINOR 0 #define ARCUS_SIGNATURE 0x2BAD #define SIG(n) (((n) & 0xffff0000) >> 16) #define SOCKET_CLOSE 0xf0f0f0f0 #ifdef ARCUS_DEBUG #define DEBUG(message) debug(message) #else #define DEBUG(message) #endif /** * Private implementation details for Socket. */ namespace Arcus { using namespace Private; class Socket::Private { public: Private() : state(SocketState::Initial) , next_state(SocketState::Initial) , received_close(false) , port(0) , thread(nullptr) { } void run(); void sendMessage(const MessagePtr& message); void receiveNextMessage(); void handleMessage(const std::shared_ptr<WireMessage>& wire_message); void checkConnectionState(); #ifdef ARCUS_DEBUG void debug(const std::string& message); #endif void error(ErrorCode::ErrorCode error_code, const std::string& message); void fatalError(ErrorCode::ErrorCode error_code, const std::string& msg); SocketState::SocketState state; SocketState::SocketState next_state; bool received_close; std::string address; uint port; std::thread* thread; std::list<SocketListener*> listeners; MessageTypeStore message_types; std::shared_ptr<Arcus::Private::WireMessage> current_message; std::deque<MessagePtr> sendQueue; std::mutex sendQueueMutex; std::deque<MessagePtr> receiveQueue; std::mutex receiveQueueMutex; Arcus::Private::PlatformSocket platform_socket; Error last_error; std::chrono::system_clock::time_point last_keep_alive_sent; static const int keep_alive_rate = 500; //Number of milliseconds between sending keepalive packets // This value determines when protobuf should warn about very large messages. static const int message_size_warning = 400 * 1048576; // This value determines when protobuf should error out because the message is too large. // Due to the way Protobuf is implemented, messages large than 512MiB will cause issues. static const int message_size_maximum = 500 * 1048576; }; #ifdef ARCUS_DEBUG void Socket::Private::debug(const std::string& message) { Error error(ErrorCode::Debug, std::string("[DEBUG] ") + message); for(auto listener : listeners) { listener->error(error); } } #endif // Report an error that should not cause the connection to abort. void Socket::Private::error(ErrorCode::ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; for(auto listener : listeners) { listener->error(error); } } // Report an error that should cause the socket to go into an error state and abort the connection. void Socket::Private::fatalError(ErrorCode::ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setFatalError(true); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; platform_socket.close(); next_state = SocketState::Error; for(auto listener : listeners) { listener->error(error); } } // Thread run method. void Socket::Private::run() { while(state != SocketState::Closed && state != SocketState::Error) { switch(state) { case SocketState::Connecting: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.connect(address, port)) { fatalError(ErrorCode::ConnectFailedError, "Could not connect to the given address"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::ConnectFailedError, "Failed to set socket receive timeout"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Opening: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.bind(address, port)) { fatalError(ErrorCode::BindFailedError, "Could not bind to the given address and port"); } else { next_state = SocketState::Listening; } break; } case SocketState::Listening: { platform_socket.listen(1); if(!platform_socket.accept()) { fatalError(ErrorCode::AcceptFailedError, "Could not accept the incoming connection"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::AcceptFailedError, "Could not set receive timeout of socket"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Connected: { //Get all the messages from the queue and store them in a temporary array so we can //unlock the queue before performing the send. std::list<MessagePtr> messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } receiveNextMessage(); if(next_state != SocketState::Error) { checkConnectionState(); } break; } case SocketState::Closing: { if(!received_close) { // We want to close the socket. // First, flush the send queue so it is empty. std::list<MessagePtr> messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } // Communicate to the other side that we want to close. platform_socket.writeUInt32(SOCKET_CLOSE); // Disable further writing to the socket. error(ErrorCode::Debug, "We got a request to close the socket."); platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // Wait until we receive confirmation from the other side to actually close. uint32_t data = 0; while(data != SOCKET_CLOSE && next_state == SocketState::Closing) { if(platform_socket.readUInt32(&data) == -1) { break; } } } else { // The other side requested a close. Drop all pending messages // since the other socket will not process them anyway. sendQueueMutex.lock(); sendQueue.clear(); sendQueueMutex.unlock(); // Send confirmation to the other side that we received their close // request and are also closing down. platform_socket.writeUInt32(SOCKET_CLOSE); // Prevent further writing to the socket. platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // At this point the socket can safely be closed, assuming that SOCKET_CLOSE // is the last data received from the other socket and everything was received // in order (which should be guaranteed by TCP). } error(ErrorCode::Debug, "Closing socket because other side requested close."); platform_socket.close(); next_state = SocketState::Closed; break; } default: break; } if(next_state != state) { state = next_state; for(auto listener : listeners) { listener->stateChanged(state); } } } } // Send a message to the connected socket. void Socket::Private::sendMessage(const MessagePtr& message) { uint32_t header = (ARCUS_SIGNATURE << 16) | (VERSION_MAJOR << 8) | (VERSION_MINOR); if(platform_socket.writeUInt32(header) == -1) { error(ErrorCode::SendFailedError, "Could not send message header"); return; } uint32_t message_size = message->ByteSize(); if(platform_socket.writeUInt32(message_size) == -1) { error(ErrorCode::SendFailedError, "Could not send message size"); return; } uint32_t type_id = message_types.getMessageTypeId(message); if(platform_socket.writeUInt32(type_id) == -1) { error(ErrorCode::SendFailedError, "Could not send message type"); return; } std::string data = message->SerializeAsString(); if(platform_socket.writeBytes(data.size(), data.data()) == -1) { error(ErrorCode::SendFailedError, "Could not send message data"); } DEBUG(std::string("Sending message of type ") + std::to_string(type_id) + " and size " + std::to_string(message_size)); } // Handle receiving data until we have a proper message. void Socket::Private::receiveNextMessage() { int result = 0; if(!current_message) { current_message = std::make_shared<WireMessage>(); } if(current_message->state == WireMessage::MessageState::Header) { uint32_t header = 0; platform_socket.readUInt32(&header); if(header == 0) // Keep-alive, just return { return; } else if(header == SOCKET_CLOSE) { // We received a close request from the other socket, so close this socket as well. next_state = SocketState::Closing; received_close = true; return; } int signature = (header & 0xffff0000) >> 16; int major_version = (header & 0x0000ff00) >> 8; int minor_version = header & 0x000000ff; if(signature != ARCUS_SIGNATURE) { // Someone might be speaking to us in a different protocol? error(ErrorCode::ReceiveFailedError, "Header mismatch"); current_message.reset(); platform_socket.flush(); return; } if(major_version != VERSION_MAJOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } if(minor_version != VERSION_MINOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } DEBUG("Incoming message, header ok"); current_message->state = WireMessage::MessageState::Size; } if(current_message->state == WireMessage::MessageState::Size) { uint32_t size = 0; result = platform_socket.readUInt32(&size); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Size invalid"); current_message.reset(); platform_socket.flush(); return; } DEBUG(std::string("Incoming message size: ") + std::to_string(size)); current_message->size = size; current_message->state = WireMessage::MessageState::Type; } if (current_message->state == WireMessage::MessageState::Type) { uint32_t type = 0; result = platform_socket.readUInt32(&type); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Receiving type failed"); current_message->valid = false; } uint32_t real_type = static_cast<uint32_t>(type); try { current_message->allocateData(); } catch (std::bad_alloc&) { // Either way we're in trouble. current_message.reset(); fatalError(ErrorCode::ReceiveFailedError, "Out of memory"); return; } DEBUG(std::string("Incoming message type: ") + std::to_string(real_type)); current_message->type = real_type; current_message->state = WireMessage::MessageState::Data; } if (current_message->state == WireMessage::MessageState::Data) { result = platform_socket.readBytes(current_message->getRemainingSize(), ¤t_message->data[current_message->received_size]); if(result < 0) { error(ErrorCode::ReceiveFailedError, "Could not receive data for message"); current_message.reset(); return; } else { current_message->received_size = current_message->received_size + result; DEBUG("Received " + std::to_string(result) + " bytes data"); if(current_message->isComplete()) { if(!current_message->valid) { current_message.reset(); return; } current_message->state = WireMessage::MessageState::Dispatch; } } } if (current_message->state == WireMessage::MessageState::Dispatch) { handleMessage(current_message); current_message.reset(); } } // Parse and process a message received on the socket. void Socket::Private::handleMessage(const std::shared_ptr<WireMessage>& wire_message) { if(!message_types.hasType(wire_message->type)) { DEBUG(std::string("Received message type: ") + std::to_string(wire_message->type)); error(ErrorCode::UnknownMessageTypeError, "Unknown message type"); return; } MessagePtr message = message_types.createMessage(wire_message->type); google::protobuf::io::ArrayInputStream array(wire_message->data, wire_message->size); google::protobuf::io::CodedInputStream stream(&array); stream.SetTotalBytesLimit(message_size_maximum, message_size_warning); if(!message->ParseFromCodedStream(&stream)) { error(ErrorCode::ParseFailedError, "Failed to parse message:" + std::string(wire_message->data)); return; } DEBUG(std::string("Received a message of type ") + std::to_string(wire_message->type) + " and size " + std::to_string(wire_message->size)); receiveQueueMutex.lock(); receiveQueue.push_back(message); receiveQueueMutex.unlock(); for(auto listener : listeners) { listener->messageReceived(); } } // Send a keepalive packet to check whether we are still connected. void Socket::Private::checkConnectionState() { auto now = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_keep_alive_sent); if(diff.count() > keep_alive_rate) { int32_t keepalive = 0; if(platform_socket.writeUInt32(keepalive) == -1) { error(ErrorCode::ConnectionResetError, "Connection reset by peer"); next_state = SocketState::Closing; } last_keep_alive_sent = now; } } } 07070100833170000081A4000003E800000064000000015A70200700000757000000080000000200000000000000000000001C00000000libArcus-3.2.20/src/Types.h/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_TYPES_H #define ARCUS_TYPES_H #include <string> #include <memory> namespace google { namespace protobuf { class Message; } } namespace Arcus { // Convenience typedef so uint can be used. typedef uint32_t uint; // Convenience typedef for standard message argument. typedef std::shared_ptr<google::protobuf::Message> MessagePtr; /** * Socket state. */ namespace SocketState { // Note: Not using enum class due to incompatibility with SIP. enum SocketState { Initial, ///< Created, not running. Connecting, ///< Connecting to an address and port. Connected, ///< Connected and capable of sending and receiving messages. Opening, ///< Opening for incoming connections. Listening, ///< Listening for incoming connections. Closing, ///< Closing down. Closed, ///< Closed, not running. Error ///< A fatal error happened that blocks the socket from operating. }; } } #endif //ARCUS_TYPES_H 07070100833172000081A4000003E800000064000000015A70200700000B97000000080000000200000000000000000000002400000000libArcus-3.2.20/src/WireMessage_p.h/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. <a.hiemstra@ultimaker.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef ARCUS_WIRE_MESSAGE_P_H #define ARCUS_WIRE_MESSAGE_P_H #include "Types.h" namespace Arcus { namespace Private { /** * Private class that encapsulates a message being sent over the wire. */ class WireMessage { public: /** * Current state of the message. */ enum class MessageState { Header, ///< Check for the header. Size, ///< Check for the message size. Type, ///< Check for the message type. Data, ///< Get the message data. Dispatch ///< Process the message and parse it into a protobuf message. }; WireMessage() : state(MessageState::Header) , size(0) , received_size(0) , valid(true) , type(0) , data(nullptr) { } inline ~WireMessage() { if(size > 0 && data) { delete[] data; } } // Current message state. MessageState state; // Size of the message. uint32_t size; // Amount of bytes received so far. uint32_t received_size; // Is this a potentially valid message? bool valid; // The type of message. uint32_t type; // The data of the message. char* data; // Return how many bytes are remaining for this message to be complete. inline uint32_t getRemainingSize() const { return size - received_size; } // Allocate data for this message based on size. inline void allocateData() { data = new char[size]; } // Check if the message can be considered complete. inline bool isComplete() const { return received_size >= size; } }; } } #endif //ARCUS_WIRE_MESSAGE_P_H 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!263 Blöcke
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor