From cc649c98d5daea1cd78d861615c8490b00e8ffd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandru=20S=C4=83vulescu?= Date: Thu, 13 Jun 2024 13:02:36 +0200 Subject: [PATCH] RAMS7200 v1.0.0 --- .gitignore | 6 + .gitmodules | 3 + CMakeLists.txt | 233 ++++++ Common/Constants.cxx | 45 + Common/Constants.hxx | 165 ++++ Common/Logger.cxx | 59 ++ Common/Logger.hxx | 118 +++ Common/S7Utils.hxx | 248 ++++++ Common/Utils.hxx | 92 ++ LICENSE | 787 ++++++++++++++++++ RAMS7200Drv.cxx | 47 ++ RAMS7200Drv.hxx | 30 + RAMS7200HWMapper.cxx | 194 +++++ RAMS7200HWMapper.hxx | 56 ++ RAMS7200HWService.cxx | 272 ++++++ RAMS7200HWService.hxx | 67 ++ RAMS7200LibFacade.cxx | 291 +++++++ RAMS7200LibFacade.hxx | 98 +++ RAMS7200MS.cxx | 61 ++ RAMS7200MS.hxx | 85 ++ RAMS7200Main.cxx | 75 ++ RAMS7200Resources.cxx | 116 +++ RAMS7200Resources.hxx | 52 ++ README.md | 268 ++++++ Transformations/RAMS7200BoolTrans.cxx | 83 ++ Transformations/RAMS7200BoolTrans.hxx | 80 ++ Transformations/RAMS7200FloatTrans.cxx | 86 ++ Transformations/RAMS7200FloatTrans.hxx | 81 ++ Transformations/RAMS7200Int16Trans.cxx | 90 ++ Transformations/RAMS7200Int16Trans.hxx | 80 ++ Transformations/RAMS7200Int32Trans.cxx | 84 ++ Transformations/RAMS7200Int32Trans.hxx | 81 ++ Transformations/RAMS7200StringTrans.cxx | 112 +++ Transformations/RAMS7200StringTrans.hxx | 63 ++ Transformations/RAMS7200Uint8Trans.cxx | 85 ++ Transformations/RAMS7200Uint8Trans.hxx | 81 ++ config.h.in | 21 + doc/RAMS7200Design.svg | 1 + doc/RAMS7200Design.uml | 106 +++ external/libsnap7 | 1 + test.cpp | 359 ++++++++ winccoa/dplist/rams7200_driver_config.dpl | 38 + winccoa/panels/para/address_rams7200.pnl | 774 +++++++++++++++++ .../scripts/libs/rams7200_dpe_addressing.ctl | 134 +++ winccoa/scripts/userDrivers.ctl | 72 ++ winccoa/scripts/userPara.ctl | 262 ++++++ 46 files changed, 6242 insertions(+) create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 CMakeLists.txt create mode 100644 Common/Constants.cxx create mode 100644 Common/Constants.hxx create mode 100644 Common/Logger.cxx create mode 100644 Common/Logger.hxx create mode 100644 Common/S7Utils.hxx create mode 100644 Common/Utils.hxx create mode 100644 LICENSE create mode 100644 RAMS7200Drv.cxx create mode 100644 RAMS7200Drv.hxx create mode 100644 RAMS7200HWMapper.cxx create mode 100644 RAMS7200HWMapper.hxx create mode 100644 RAMS7200HWService.cxx create mode 100644 RAMS7200HWService.hxx create mode 100644 RAMS7200LibFacade.cxx create mode 100644 RAMS7200LibFacade.hxx create mode 100644 RAMS7200MS.cxx create mode 100644 RAMS7200MS.hxx create mode 100644 RAMS7200Main.cxx create mode 100644 RAMS7200Resources.cxx create mode 100644 RAMS7200Resources.hxx create mode 100644 README.md create mode 100644 Transformations/RAMS7200BoolTrans.cxx create mode 100644 Transformations/RAMS7200BoolTrans.hxx create mode 100644 Transformations/RAMS7200FloatTrans.cxx create mode 100644 Transformations/RAMS7200FloatTrans.hxx create mode 100644 Transformations/RAMS7200Int16Trans.cxx create mode 100644 Transformations/RAMS7200Int16Trans.hxx create mode 100644 Transformations/RAMS7200Int32Trans.cxx create mode 100644 Transformations/RAMS7200Int32Trans.hxx create mode 100644 Transformations/RAMS7200StringTrans.cxx create mode 100644 Transformations/RAMS7200StringTrans.hxx create mode 100644 Transformations/RAMS7200Uint8Trans.cxx create mode 100644 Transformations/RAMS7200Uint8Trans.hxx create mode 100644 config.h.in create mode 100644 doc/RAMS7200Design.svg create mode 100644 doc/RAMS7200Design.uml create mode 160000 external/libsnap7 create mode 100644 test.cpp create mode 100644 winccoa/dplist/rams7200_driver_config.dpl create mode 100644 winccoa/panels/para/address_rams7200.pnl create mode 100644 winccoa/scripts/libs/rams7200_dpe_addressing.ctl create mode 100644 winccoa/scripts/userDrivers.ctl create mode 100644 winccoa/scripts/userPara.ctl diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a583501 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.o +*.gcno +*.gcda +**/*.log +.vscode +build diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..baa52b8 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "external/libsnap7"] + path = external/libsnap7 + url = git@github.com:max-dark/libsnap7.git diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..4862e55 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,233 @@ +# © Copyright 2024 CERN +# +# This software is distributed under the terms of the +# GNU Lesser General Public Licence version 3 (LGPL Version 3), +# copied verbatim in the file “LICENSE” +# +# In applying this licence, CERN does not waive the privileges +# and immunities granted to it by virtue of its status as an +# Intergovernmental Organization or submit itself to any jurisdiction. +# +# Author: Alexandru Savulescu (HSE) + +cmake_minimum_required(VERSION 3.17) + +project( + WCCOARAMS7200 + DESCRIPTION "RAMS7200 driver for WinCC OA" + LANGUAGES CXX +) + +set(PROJECT_VERSION 1.0.0) + +configure_file(config.h.in configured/config.h) +include_directories(${CMAKE_CURRENT_BINARY_DIR}/configured) +set(DRV_VERSION ${PROJECT_VERSION}) + +set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) +set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +else() + # if Coverage is selected, look for required tools + if(CMAKE_BUILD_TYPE STREQUAL "Coverage") + find_program(LCOV_PATH lcov) + if(NOT LCOV_PATH) + message(FATAL_ERROR "lcov not found! Cannot build coverage.") + endif() + endif() + # Code coverage report target + add_custom_target(coverage + COMMAND lcov --capture --directory . --output-file coverage.info + COMMAND lcov --remove coverage.info '/usr/*' '*/test/*' '*/CMakeFiles/*' --output-file coverage.info.cleaned + COMMAND genhtml coverage.info.cleaned --output-directory coverage + COMMAND xdg-open coverage/index.html + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT "Generating code coverage report..." + USES_TERMINAL + ) +endif() + +set(CMAKE_CXX_FLAGS "-rdynamic") +set(CMAKE_CXX_FLAGS_DEBUG "-O0 -ggdb") +set(CMAKE_CXX_FLAGS_COVERAGE "-O0 -g --coverage -fPIC") +set(CMAKE_CXX_FLAGS_RELEASE "-O3") + + +# Define target +set(TARGET ${PROJECT_NAME}) + +# Include WinCC_OA API +set(API_ROOT "$ENV{API_ROOT}" CACHE FILEPATH "directory of the WinCC_OA API installation") +include(${API_ROOT}/CMakeDefines.txt) + +# Collect sources +file(GLOB RAMS7200_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/RAMS7200*.cxx) +file(GLOB RAMS7200_TRANSFORMATIONS ${CMAKE_CURRENT_SOURCE_DIR}/Transformations/RAMS7200*.cxx) +file(GLOB RAMS7200_COMMON ${CMAKE_CURRENT_SOURCE_DIR}/Common/*.cxx) +set(SOURCES ${RAMS7200_SOURCES} ${RAMS7200_TRANSFORMATIONS} ${RAMS7200_COMMON}) + +# Add driver +add_driver(${TARGET} ${SOURCES}) + +# Snap7 library +if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/external/libsnap7/CMakeLists.txt) + message(STATUS "Initializing snap7 submodule...") + execute_process(COMMAND git submodule update --init --recursive external/libsnap7 + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) +endif() +add_subdirectory(external/libsnap7) +target_link_libraries(${TARGET} snap7++) +set(snap7_lib $) +# copy snap7 library to lib/ folder +add_custom_command(TARGET ${TARGET} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${snap7_lib} + $/lib/$ + COMMENT "Copying ${snap7_lib} to $/lib/$" +) + +set_target_properties(${TARGET} PROPERTIES INSTALL_RPATH "$ORIGIN/lib") + +# PVSS_PROJ_PATH Install +# Check if PVSS_PROJ_PATH is set +if(NOT DEFINED ENV{PVSS_PROJ_PATH}) + message(WARNING "PVSS_PROJ_PATH environment variable is not set. Commodity targets will not be available (install, run, valgrind).") +else() + # Install driver to PVSS_PROJ_PATH/bin + install(TARGETS ${TARGET} DESTINATION $ENV{PVSS_PROJ_PATH}/bin) + # Install snap7 library alongside the driver + install(FILES ${snap7_lib} DESTINATION $ENV{PVSS_PROJ_PATH}/bin/lib) + + # PVSS_PROJ_PATH contains the project name , so we can extract it + string(REGEX MATCH "([^/]+)/?$" PVSS_PROJECT_NAME $ENV{PVSS_PROJ_PATH}) + string(REGEX REPLACE "/$" "" PVSS_PROJECT_NAME ${PVSS_PROJECT_NAME}) + message(STATUS "PVSS project name extracted from $PVSS_PROJ_PATH ($ENV{PVSS_PROJ_PATH}): ${PVSS_PROJECT_NAME}") + + # Try to parse config/progs file to extract driver number and its config file + # i.e. WCCOARAMS7200 | always | 30 | 3 | 1 |-num 32 +config config.rams7200 + if(NOT EXISTS $ENV{PVSS_PROJ_PATH}/config/progs) + message(WARNING "Cannot find $PVSS_PROJ_PATH/config/progs. Setting driver number to 999.") + set(DRIVER_NUMBER 999) + else() + # Extract driver number and config file from config/progs + if(EXISTS $ENV{PVSS_PROJ_PATH}/config/progs) + file(STRINGS "$ENV{PVSS_PROJ_PATH}/config/progs" PROGS) + foreach(PROG ${PROGS}) + string(REGEX MATCHALL "${TARGET}.*-num ([0-9]+) \\+config (config\\..*)" DRIVER_MATCH ${PROG}) + if(DRIVER_MATCH) + set(DRIVER_NUMBER ${CMAKE_MATCH_1}) + set(DRIVER_CONFIG_FILE ${CMAKE_MATCH_2}) + message(STATUS "Driver number extracted from $ENV{PVSS_PROJ_PATH}/config/progs: ${DRIVER_NUMBER}") + message(STATUS "Driver config file extracted from $ENV{PVSS_PROJ_PATH}/config/progs: ${DRIVER_CONFIG_FILE}") + break() + endif() + endforeach() + endif() + if(NOT DEFINED DRIVER_NUMBER) + message(WARNING "Driver number could not be extracted from $PVSS_PROJ_PATH/config/progs. Setting it to 999.") + set(DRIVER_NUMBER 999) + endif() + endif() + + # Run local build target (useful for debugging, coverage, valgrind, etc.) + set(RUNBUILD_ARGS "-num ${DRIVER_NUMBER} -proj ${PVSS_PROJECT_NAME} +config $ENV{PVSS_PROJ_PATH}/config/${DRIVER_CONFIG_FILE} &") + separate_arguments(RUNBUILD_ARGS) + add_custom_target(run + COMMAND ${TARGET} ${RUNBUILD_ARGS} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT "Launching: ${TARGET} ${RUNBUILD_ARGS}" + USES_TERMINAL + COMMAND_EXPAND_LISTS + ) + add_dependencies(run ${TARGET}) + + # valgrind target + find_program(VALGRIND_PATH valgrind) + if(VALGRIND_PATH) + set(VALGRIND_CMD ${VALGRIND_PATH} "--leak-check=full" "--show-leak-kinds=all" "--track-origins=yes" "--verbose" "--log-file=valgrind.log" "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}" ${RUNBUILD_ARGS}) + add_custom_target(valgrind + COMMAND ${VALGRIND_CMD} + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT "Launching: ${VALGRIND_CMD} \n\t Log file: ${CMAKE_BINARY_DIR}/valgrind.log. \n\t Use `kill` target to stop the process." + USES_TERMINAL + COMMAND_EXPAND_LISTS + ) + add_dependencies(valgrind ${TARGET}) + endif() + +endif() + +# Send SIGTERM to the driver or valgrind process +add_custom_target(kill + COMMAND pkill -SIGTERM -u "$ENV{USER}" -f "${TARGET}" -e + COMMENT "Sending SIGTERM for ${TARGET}. WinCC OA will restart it automatically if configured to `always`." + USES_TERMINAL +) + +# Clean and update driver +add_custom_target(update + COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target clean + COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target install + COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target kill +) + +# test target (test.cpp that neeeds snap7.h and link to snap7) +add_executable(test test.cpp) +target_link_libraries(test snap7++) +set_target_properties(test PROPERTIES INSTALL_RPATH "$") +set(IP "172.18.130.170" CACHE STRING "IP of the PLC for test") +set(RACK "0" CACHE STRING "Rack of the PLC for test") +set(SLOT "0" CACHE STRING "Slot of the PLC for test") + + +add_custom_target(run_test + COMMAND ${CMAKE_CURRENT_BINARY_DIR}/test ${IP} ${RACK} ${SLOT} 2>&1 | tee test.log + COMMAND echo Done + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + COMMENT "Launching: ${CMAKE_CURRENT_BINARY_DIR}/test with args: ${IP} ${RACK} ${SLOT}. Dumping output to test.log" + USES_TERMINAL +) +add_dependencies(run_test test) + +# Config summary +message(STATUS "") +message(STATUS "---------------+-----------------------------------------------------------------------------------------------") +message(STATUS "Configured ${TARGET} ${DRV_VERSION}") +message(STATUS "---------------+-----------------------------------------------------------------------------------------------") +message(STATUS " Target | Description") +message(STATUS "---------------+-----------------------------------------------------------------------------------------------") +message(STATUS " kill | Kills ${TARGET}") +message(STATUS " update | Calls following targets: clean -> install -> kill") +if(DEFINED ENV{PVSS_PROJ_PATH}) + message(STATUS " install | Will install ${TARGET} ${PROJECT_VERSION} in: $ENV{PVSS_PROJ_PATH}/bin") + message(STATUS " | + ${snap7_lib} alongside it, in $ENV{PVSS_PROJ_PATH}/bin/lib") + message(STATUS " run | Runs ${TARGET} from ${CMAKE_BINARY_DIR} with:") + message(STATUS " | ${TARGET} -num -proj +config ") + message(STATUS " | pvss_project_name = ${PVSS_PROJECT_NAME}") + message(STATUS " | driver_number = ${DRIVER_NUMBER}") + message(STATUS " | driver_config_file = $ENV{PVSS_PROJ_PATH}/config/${DRIVER_CONFIG_FILE}") +else() + message(STATUS " install | PVSS_PROJ_PATH environment variable was not set. Cannot install from CMake.") + message(STATUS " run | PVSS_PROJ_PATH environment variable was not set. Cannot run local build from CMake.") +endif() +if(VALGRIND_PATH) + message(STATUS " valgrind | Runs ${TARGET} from ${CMAKE_BINARY_DIR} with valgrind.") + message(STATUS " | (similar to run target)") +else() + message(STATUS " valgrind | Not available. valgrind or PVSS_PROJ_PATH not found.") +endif() +if(CMAKE_BUILD_TYPE STREQUAL "Coverage") + message(STATUS " coverage | Generates code coverage report (requires lcov)") +else() + message(STATUS " coverage | Not available. Build type is not Coverage -> -DCMAKE_BUILD_TYPE=Coverage. lcov required.") +endif() +message(STATUS " run_test | Runs test (test.cpp) with the following args: ") +message(STATUS " | IP: ${IP} RACK: ${RACK} SLOT: ${SLOT}") +message(STATUS " | You can change them with -DIP= -DRACK= -DSLOT=") +message(STATUS "---------------+-----------------------------------------------------------------------------------------------") diff --git a/Common/Constants.cxx b/Common/Constants.cxx new file mode 100644 index 0000000..82b9d01 --- /dev/null +++ b/Common/Constants.cxx @@ -0,0 +1,45 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include "Constants.hxx" +#include "Logger.hxx" +#include "Utils.hxx" +#include "config.h" +#include + +namespace Common { + + std::string Constants::drv_name = "RAMS7200"; + uint32_t Constants::DRV_NO = 0; // Read from PVSS on driver startup + uint32_t Constants::TSAP_PORT_LOCAL = 0; // Read from PVSS on driver startup from config file + uint32_t Constants::TSAP_PORT_REMOTE = 0; // Read from PVSS on driver startupconfig file + uint32_t Constants::POLLING_INTERVAL = 2; // Read from PVSS on driver startupconfig file, default 2 seconds + uint32_t Constants::MAX_IO_FAILURES = 5; // Read from PVSS on driver startupconfig file, default 2 seconds + uint32_t Constants::CYCLE_INTERVAL = 1; // Read from PVSS on driver startupconfig file, default 1 second + bool Constants::SMOOTHING = true; // Read from PVSS on driver startupconfig file + std::string Constants::drv_version = PROJECT_VER; + + // The map can be used to map a callback to a HwObject address + std::map> Constants::parse_map = + { + { "_DEBUGLVL", + [](const char* data) + { + int16_t retVal = Common::Utils::CopyNSwapBytes(data); + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "setLogLvl :",std::to_string(retVal).c_str()); + Common::Logger::setLogLvl(retVal); + } + } + }; +} diff --git a/Common/Constants.hxx b/Common/Constants.hxx new file mode 100644 index 0000000..dd77e1b --- /dev/null +++ b/Common/Constants.hxx @@ -0,0 +1,165 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef CONSTANTS_HXX_ +#define CONSTANTS_HXX_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Common{ + + /*! + * \class Constants + * \brief Class containing constant values used in driver + */ + class Constants{ + public: + + static void setDrvName(std::string lp); + static std::string& getDrvName(); + + static std::string& getDrvVersion(); + + // called in driver init to set the driver number dynamically + static void setDrvNo(uint32_t no); + // subsequentally called when writing buffers etc. + static uint32_t getDrvNo(); + + static void setLocalTsapPort(uint32_t port); + static const uint32_t& getLocalTsapPort(); + + static void setRemoteTsapPort(uint32_t port); + static const uint32_t& getRemoteTsapPort(); + + static void setPollingInterval(uint32_t pollingInterval); + static const uint32_t& getPollingInterval(); + + static const std::map>& GetParseMap(); + + static uint32_t getMsCopyPort(); + + static void setSmoothing(bool smoothing); + static bool getSmoothing(); + + static uint32_t getMaxIoFailures(); + static void setMaxIoFailures(uint32_t maxIoFailures); + + static uint32_t getCycleInterval(); + static void setCycleInterval(uint32_t cycleInterval); + + private: + static std::string drv_name; + static std::string drv_version; + static uint32_t DRV_NO; // WinCC OA manager number + static uint32_t TSAP_PORT_LOCAL; + static uint32_t TSAP_PORT_REMOTE; + static uint32_t POLLING_INTERVAL; + static bool SMOOTHING; + static uint32_t MAX_IO_FAILURES; + static uint32_t CYCLE_INTERVAL; + + static std::map> parse_map; + }; + + inline const std::map>& Constants::GetParseMap() + { + return parse_map; + } + + inline void Constants::setDrvName(std::string dname){ + drv_name = dname; + } + + inline std::string& Constants::getDrvName(){ + return drv_name; + } + + inline std::string& Constants::getDrvVersion(){ + return drv_version; + } + + inline void Constants::setDrvNo(uint32_t no){ + DRV_NO = no; + } + + inline uint32_t Constants::getDrvNo(){ + return DRV_NO; + } + + inline void Constants::setLocalTsapPort(uint32_t port){ + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"Setting TSAP_PORT_LOCAL=" + CharString(port)); + TSAP_PORT_LOCAL = port; + } + + inline const uint32_t& Constants::getLocalTsapPort(){ + return TSAP_PORT_LOCAL; + } + + inline void Constants::setRemoteTsapPort(uint32_t port){ + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"Setting TSAP_PORT_REMOTE=" + CharString(port)); + TSAP_PORT_REMOTE = port; + } + + inline const uint32_t& Constants::getRemoteTsapPort(){ + return TSAP_PORT_REMOTE; + } + + inline void Constants::setPollingInterval(uint32_t pollingInterval) + { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"Setting POLLING_INTERVAL=" + CharString(pollingInterval)); + POLLING_INTERVAL = pollingInterval; + } + + inline const uint32_t& Constants::getPollingInterval() + { + return POLLING_INTERVAL; + } + + inline void Constants::setSmoothing(bool smoothing) { + SMOOTHING = smoothing; + } + + inline bool Constants::getSmoothing() { + return SMOOTHING; + } + + inline uint32_t Constants::getMaxIoFailures() { + return MAX_IO_FAILURES; + } + + inline void Constants::setMaxIoFailures(uint32_t maxIoFailures) { + MAX_IO_FAILURES = maxIoFailures; + } + + inline uint32_t Constants::getCycleInterval() { + return CYCLE_INTERVAL; + } + + inline void Constants::setCycleInterval(uint32_t cycleInterval) { + CYCLE_INTERVAL = cycleInterval; + } + +}//namespace +#endif /* CONSTANTS_HXX_ */ diff --git a/Common/Logger.cxx b/Common/Logger.cxx new file mode 100644 index 0000000..b6e3b5d --- /dev/null +++ b/Common/Logger.cxx @@ -0,0 +1,59 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include "Logger.hxx" +#include "Common/Constants.hxx" +#include + +namespace Common { + +int16_t Logger::loggingLevel = 1; +const char * Logger::timestrformat = "%a, %d.%m.%Y %H:%M:%S"; + +void Logger::globalInfo(int lvl, const char *note1, const char* note2, const char* note3){ + if(loggingLevel > 0 && loggingLevel >= lvl){ + ErrHdl::error( + ErrClass::PRIO_INFO, + ErrClass::ERR_CONTROL, + ErrClass::NOERR, + note1, + note2, + note3); + } +} + +void Logger::globalWarning(const char *note1, const char* note2, const char* note3){ + if(loggingLevel > L0){ + ErrHdl::error( + ErrClass::PRIO_WARNING, + ErrClass::ERR_CONTROL, + ErrClass::NOERR, + note1, + note2, + note3); + } +} + +void Logger::globalError(const char *note1, const char* note2, const char* note3){ + if(loggingLevel > L0){ + ErrHdl::error( + ErrClass::PRIO_FATAL, + ErrClass::ERR_CONTROL, + ErrClass::NOERR, + note1, + note2, + note3); + } +} +} diff --git a/Common/Logger.hxx b/Common/Logger.hxx new file mode 100644 index 0000000..8a422f0 --- /dev/null +++ b/Common/Logger.hxx @@ -0,0 +1,118 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef DEBUGMETHODS_HXX +#define DEBUGMETHODS_HXX + +#include +#include + +#include +#include + +#include + +using std::mutex; +using std::lock_guard; + +namespace Common { + +/*! + * \class Debug + * \brief Class is handling writing to starndard output debuge informations provided by user. + * Class is singleton and has overloaded operator << (). + * + * \see operator <<() + */ +class Logger{ +public: + Logger() : creationTime(0), logNum(0), devNum(0), prefix(""){ + }; + + Logger(int devNum):creationTime(0), logNum(0), devNum(devNum){ + updatePrefix(); + }; + + ~Logger(); + + /*! + * Change of global logger info level + * \param new logging level + */ + static void setLogLvl(int16_t lvl); + + /*! + * Setting number of device to which logger is binded + * \param device number + */ + void setDevNum(int num); + + static void globalInfo(int lvl, const char *note1 = NULL, const char* note2 = NULL, const char* note3 = NULL); + + static void globalWarning(const char *note1 = NULL, const char* note2 = NULL, const char* note3 = NULL); + + static void globalError(const char *note1 = NULL, const char* note2 = NULL, const char* note3 = NULL); + + static const int L0 = 0; + static const int L1 = 1; + static const int L2 = 2; + static const int L3 = 3; + static const int L4 = 4; + + static const int getLogLevel(); +private: + + std::fstream& getStream(); + + void closeStream(); + + void updatePrefix(); + + static int16_t loggingLevel; + + std::fstream f; + long creationTime; + int logNum; + + int devNum; + + std::string prefix; + + static const char * timestrformat; + + mutex localVariableDataAccess; +}; + + +inline void Logger::setLogLvl(int16_t lvl){ + loggingLevel = lvl; +} + + +inline const int Logger::getLogLevel(){ + return loggingLevel; +} + +inline void Logger::setDevNum(int num){ + lock_guard raiiLock(localVariableDataAccess); + devNum = num; + updatePrefix(); +} + +inline void Logger::updatePrefix(){ + prefix = devNum? (char *)("[MS " + CharString(devNum) + "] "): ""; +} + +}//namespace +#endif /* DEBUGMETHODS_HXX_ */ diff --git a/Common/S7Utils.hxx b/Common/S7Utils.hxx new file mode 100644 index 0000000..58bf821 --- /dev/null +++ b/Common/S7Utils.hxx @@ -0,0 +1,248 @@ +/** © Copyright 2023 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Alexandru Savulescu (HSE) + * + **/ +#pragma once + +#include +#include +#include "snap7.h" +#include +#include +#include "Common/Utils.hxx" + +namespace Common{ + class S7Utils{ + public: + enum class Operation: int {READ = 0, WRITE = 1}; + static int AddressGetArea(const std::string& Address) + { + if(Address.length() < 2){ + return -1; //invalid + } + switch(std::toupper(Address[0])) + { + case 'V': //Data Blocks + return S7AreaDB; + case 'I': + case 'E': //Inputs + return S7AreaPE; + case 'Q': + case 'A': //Outputs + return S7AreaPA; + case 'M': + case 'F': //Flag memory + return S7AreaMK; + case 'T': //Timers + return S7AreaTM; + case 'C': + case 'Z': //Counters + return S7AreaCT; + default: + return -1; //invalid + } + + return 0; //dummy + } + + static int AddressGetWordLen(const std::string& Address) + { + if(Address.length() < 2){ + return -1; //invalid + } + switch(std::toupper(Address[1])) + { + case 'B': + return S7WLByte; + case 'W': + return S7WLWord; + case 'D': + return S7WLReal; //e.g. VD124 GLB.CAL.GANA1 + default: + return S7WLBit; //e.g.: V255.3 + } + return 0; //dummy + } + + + static int AddressGetStart(const std::string& Address) + { + if(Address.length() < 2){ + return -1; //invalid + } + switch(std::toupper(Address[1])) + { + case 'B': + case 'W': + case 'D': + //Addesses like XX9999 + if(Address.find_first_of('.') == std::string::npos){ + return std::stoi(Address.substr(2)); //e.g.:VB2978 + } + else{ + return std::stoi(Address.substr(2, Address.find_first_of('.')-1)); //e.g.:VB2978.20 + } + break; + default: + //Addesses like X9999 + if(Address.find_first_of('.') == std::string::npos){ + return -1; //invalid + } + else{ + return std::stoi(Address.substr(1, Address.find_first_of('.')-1)); //e.g.: V255.3 + } + break; + } + + return 0; //dummy + } + + + + static int AddressGetAmount(const std::string& Address) + { + if(Address.length() < 2){ + return -1; //invalid + } + if(std::toupper(Address[1]) == 'B' && Address.find_first_of('.') != std::string::npos){ + return std::stoi(Address.substr(Address.find('.')+1)); + } + return 1; //default + } + + static int AddressGetBit(const std::string& Address) + { + if(Address.length() < 2){ + return -1; //invalid + } + if(AddressGetWordLen(Address) == S7WLBit && Address.find_first_of('.') != std::string::npos){ + return std::stoi(Address.substr(Address.find('.')+1)); + } + + return 0; //default + } + + static int DataSizeByte(int WordLength) + { + switch (WordLength){ + case S7WLBit : return 1; // S7 sends 1 byte per bit + case S7WLByte : return 1; + case S7WLWord : return 2; + case S7WLDWord : return 4; + case S7WLReal : return 4; + case S7WLCounter : return 2; + case S7WLTimer : return 2; + default : return 0; + } + } + + static bool AddressIsValid(const std::string& Address){ + return AddressGetArea(Address)!=-1 && + AddressGetWordLen(Address)!=-1 && + AddressGetAmount(Address)!=-1 && + AddressGetStart(Address)!=-1; + } + + static std::string DisplayTS7DataItem(const PS7DataItem& item, Operation op = Operation::READ) + { + const std::string opStr = op == Operation::READ ? "READ" : "WRITE"; + std::stringstream ss; + if (!item->pdata){ + ss << "-->" << opStr << " : pdata is null"; + return ss.str(); + } + switch(item->WordLen){ + case S7WLByte: + if(item->Amount>1){ + std::string strVal(reinterpret_cast(item->pdata), reinterpret_cast(item->pdata) + item->Amount); + ss << "--> " << opStr << " value as string :'" << strVal << "'"; + } + else{ + uint8_t byteVal; + std::memcpy(&byteVal, item->pdata , sizeof(uint8_t)); + ss << "--> " << opStr << " value as byte : " << static_cast(byteVal) << ""; + } + break; + case S7WLWord: + { + uint16_t wordVal = Common::Utils::CopyNSwapBytes(item->pdata); + ss << "--> " << opStr << " value as word : " << wordVal << ""; + break; + } + case S7WLReal: + { + float realVal = Common::Utils::CopyNSwapBytes(item->pdata); + ss << "--> " << opStr << " value as real : " << std::fixed << std::setprecision(3) << realVal << ""; + break; + } + case S7WLBit: + { + uint8_t bitVal; + std::memcpy(&bitVal, item->pdata , sizeof(uint8_t)); + ss << "--> " << opStr << " value as bit : " << static_cast(bitVal) << ""; + break; + } + default: + ss << "--> " << opStr << " : unknown WordLen"; + break; + } + + return ss.str(); + } + + static TS7DataItem TS7DataItemFromAddress(const std::string& Address, bool allocateMemory = false){ + TS7DataItem item; + item.Area = AddressGetArea(Address); + item.WordLen = AddressGetWordLen(Address); + item.DBNumber = 1; + item.Start = item.WordLen == S7WLBit ? (AddressGetStart(Address)*8)+AddressGetBit(Address) : AddressGetStart(Address); + item.Amount = AddressGetAmount(Address); + item.Result = -1; + if(allocateMemory) + { + TS7AllocateDataItemForAddress(item); + } + else + { + item.pdata = nullptr; + } + return item; + } + + static TS7DataItem TS7DataItemShallowClone(const TS7DataItem& item){ + TS7DataItem newItem; + newItem.Area = item.Area; + newItem.WordLen = item.WordLen; + newItem.DBNumber = item.DBNumber; + newItem.Start = item.Start; + newItem.Amount = item.Amount; + newItem.pdata = nullptr; + newItem.Result = -1; + TS7AllocateDataItemForAddress(newItem); + return newItem; + } + + static void TS7AllocateDataItemForAddress(TS7DataItem& item){ + if(item.pdata){ + delete[] static_cast(item.pdata); + } + item.pdata = new char[DataSizeByte(item.WordLen )*item.Amount]; + std::memset(item.pdata, 0, DataSizeByte(item.WordLen )*item.Amount); + } + + static int GetByteSizeFromAddress(const std::string& Address) + { + TS7DataItem item = TS7DataItemFromAddress(Address); + return (DataSizeByte(item.WordLen )*item.Amount); + } + }; //class S7Utils +} //namespace Common \ No newline at end of file diff --git a/Common/Utils.hxx b/Common/Utils.hxx new file mode 100644 index 0000000..84d50b5 --- /dev/null +++ b/Common/Utils.hxx @@ -0,0 +1,92 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef UTILS_HXX +#define UTILS_HXX + + +#include +#include +#include +#include +#include +#include +#include +#include + +template +std::ostream& operator << (std::ostream& os, const std::vector& iterable) +{ + for (auto & i : iterable) + os << i << " "; + return os; +} + + +namespace Common { + +using std::future; +using std::future_status; +using std::cout; +using std::exception; +using std::endl; + +class Utils +{ +public: + + Utils() = delete; + + static auto split(const std::string& str, char delimiter = '$') -> std::vector + { + std::vector result; + std::size_t previous = 0; + std::size_t current = 0; + + while ((current = str.find(delimiter, previous))!= std::string::npos) { + result.emplace_back(str.substr(previous, current - previous)); + previous = current + 1; + } + + result.emplace_back(str.substr(previous)); + + return result; + } + + template + static T CopyNSwapBytes(const T& value) + { + T retVal; + std::memcpy(reinterpret_cast(&retVal), reinterpret_cast(&value), sizeof(T)); + std::reverse(reinterpret_cast(&retVal), reinterpret_cast(&retVal) + sizeof(T)); + return retVal; + } + + template + static T CopyNSwapBytes(const void* value) + { + return CopyNSwapBytes(*reinterpret_cast(value)); + } + + template + static T CopyNSwapBytes(const char* value) + { + return CopyNSwapBytes(*static_cast(static_cast(value))); + } + + +}; + +} +#endif // UTILS_HXX diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e750f3a --- /dev/null +++ b/LICENSE @@ -0,0 +1,787 @@ +GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +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. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU 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 +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/RAMS7200Drv.cxx b/RAMS7200Drv.cxx new file mode 100644 index 0000000..5aef875 --- /dev/null +++ b/RAMS7200Drv.cxx @@ -0,0 +1,47 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include +#include +#include + +#include + +//------------------------------------------------------------------------------------ + +void RAMS7200Drv::install_HWMapper() +{ + hwMapper = new RAMS7200HWMapper; +} + +//-------------------------------------------------------------------------------- + +void RAMS7200Drv::install_HWService() +{ + hwService = new RAMS7200HWService; +} + +//-------------------------------------------------------------------------------- + +HWObject * RAMS7200Drv::getHWObject() const +{ + return new HWObject(); +} + +//-------------------------------------------------------------------------------- + +void RAMS7200Drv::install_AlertService() +{ + DrvManager::install_AlertService(); +} diff --git a/RAMS7200Drv.hxx b/RAMS7200Drv.hxx new file mode 100644 index 0000000..6c25fe5 --- /dev/null +++ b/RAMS7200Drv.hxx @@ -0,0 +1,30 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200DRV_H_ +#define RAMS7200DRV_H_ + +#include + +class RAMS7200Drv : public DrvManager +{ + public: + virtual void install_HWMapper(); + virtual void install_HWService(); + virtual void install_AlertService(); + + virtual HWObject *getHWObject() const; +}; + +#endif diff --git a/RAMS7200HWMapper.cxx b/RAMS7200HWMapper.cxx new file mode 100644 index 0000000..708604c --- /dev/null +++ b/RAMS7200HWMapper.cxx @@ -0,0 +1,194 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include "RAMS7200HWMapper.hxx" +#include "Transformations/RAMS7200StringTrans.hxx" +#include "Transformations/RAMS7200Int16Trans.hxx" +#include "Transformations/RAMS7200Int32Trans.hxx" +#include "Transformations/RAMS7200FloatTrans.hxx" +#include "Transformations/RAMS7200BoolTrans.hxx" +#include "Transformations/RAMS7200Uint8Trans.hxx" +#include "RAMS7200HWService.hxx" + +#include +#include +#include "Common/Logger.hxx" +#include "Common/Constants.hxx" +#include "Common/Utils.hxx" +#include "Common/S7Utils.hxx" +#include // DEBUG macros + + +//-------------------------------------------------------------------------------- +// We get new configs here. Create a new HW-Object on arrival and insert it. + +PVSSboolean RAMS7200HWMapper::addDpPa(DpIdentifier &dpId, PeriphAddr *confPtr) +{ + // We don't use Subindices here, so its simple. + // Otherwise we had to look if we already have a HWObject and adapt its length. + + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "With Direction: " + CharString(confPtr->getDirection()) + ", addDpPa called for " + confPtr->getName().c_str()); + + // tell the config how we will transform data to/from the device + // by installing a Transformation object into the PeriphAddr + // In this template, the Transformation type was set via the + // configuration panel (it is already set in the PeriphAddr) + + switch (confPtr->getTransformationType()) { + case TransUndefinedType: + Common::Logger::globalInfo(Common::Logger::L1, __PRETTY_FUNCTION__, "Undefined transformation" + CharString(confPtr->getTransformationType()) +", For address: "+ confPtr->getName()); + return HWMapper::addDpPa(dpId, confPtr); + case RAMS7200DrvBoolTransType: + Common::Logger::globalInfo(Common::Logger::L3,"Bool transformation"); + confPtr->setTransform(new Transformations::RAMS7200BoolTrans); + break; + case RAMS7200DrvUint8TransType: + Common::Logger::globalInfo(Common::Logger::L3,"Uint8 transformation"); + confPtr->setTransform(new Transformations::RAMS7200Uint8Trans); + break; + case RAMS7200DrvInt32TransType: + Common::Logger::globalInfo(Common::Logger::L3,"Int32 transformation"); + confPtr->setTransform(new Transformations::RAMS7200Int32Trans); + break; + case RAMS7200DrvInt16TransType: + Common::Logger::globalInfo(Common::Logger::L3,"Int16 transformation"); + confPtr->setTransform(new Transformations::RAMS7200Int16Trans); + break; + case RAMS7200DrvFloatTransType: + Common::Logger::globalInfo(Common::Logger::L3,"Float transformation"); + confPtr->setTransform(new Transformations::RAMS7200FloatTrans); + break; + case RAMS7200DrvStringTransType: + Common::Logger::globalInfo(Common::Logger::L3,"String transformation"); + confPtr->setTransform(new Transformations::RAMS7200StringTrans); + break; + default: + Common::Logger::globalError("RAMS7200HWMapper::addDpPa", CharString("Illegal transformation type ") + CharString((int) confPtr->getTransformationType())); + return HWMapper::addDpPa(dpId, confPtr); + } + + + // First add the config, then the HW-Object + if ( !HWMapper::addDpPa(dpId, confPtr) ) // FAILED !! + { + Common::Logger::globalInfo(Common::Logger::L1, __PRETTY_FUNCTION__, "Failed in adding DP Para to HW Mapper object for address : " + CharString(confPtr->getName())); + return PVSS_FALSE; + } + + std::vector addressOptions = Common::Utils::split(confPtr->getName().c_str()); + + HWObject *hwObj = new HWObject; + // Set Address and Subindex + Common::Logger::globalInfo(Common::Logger::L3, "New Object", "name:" + confPtr->getName()); + hwObj->setConnectionId(confPtr->getConnectionId()); + hwObj->setAddress(confPtr->getName()); // Resolve the HW-Address, too + + // Set the data type. + hwObj->setType(confPtr->getTransform()->isA()); + + // Set the len needed for data from _all_ subindices of this PVSS-Address. + // Because we will deal with subix 0 only this is the Transformation::itemSize + hwObj->setDlen(confPtr->getTransform()->itemSize()); + // Add it to the list + addHWObject(hwObj); + + if( (confPtr->getDirection() == DIRECTION_IN || confPtr->getDirection() == DIRECTION_INOUT) && (addressOptions.size() == 3) ) { + if(!Common::S7Utils::AddressIsValid(addressOptions[1])){ + Common::Logger::globalError(__PRETTY_FUNCTION__, "Address is not valid!", CharString(confPtr->getName())); + return PVSS_FALSE; + } + // TODO: add warning if requested transformation is not the same as the s7 type + addAddress(addressOptions[0], addressOptions[1], addressOptions[2]); + } + + return PVSS_TRUE; +} + +//-------------------------------------------------------------------------------- + +PVSSboolean RAMS7200HWMapper::clrDpPa(DpIdentifier &dpId, PeriphAddr *confPtr) +{ + Common::Logger::globalInfo(Common::Logger::L3, "clrDpPa called for" + confPtr->getName()); + + std::vector addressOptions = Common::Utils::split(confPtr->getName().c_str()); + + // Find our HWObject via a template` + HWObject adrObj; + adrObj.setAddress(confPtr->getName()); + + // Lookup HW-Object via the Name, not via the HW-Address + // The class type isn't important here + HWObject *hwObj = findHWAddr(&adrObj); + + if(hwObj == NULL) { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "Error in getting HW Address"); + return PVSS_FALSE; + } + + if(confPtr->getDirection() == DIRECTION_IN || confPtr->getDirection() == DIRECTION_INOUT) + { + if (addressOptions.size() == 3) // IP + VAR + POLLTIME + { + removeAddress(addressOptions[0], addressOptions[1], addressOptions[2]); + } + } + + if ( hwObj ) { + // Object exists, remove it from the list and delete it. + clrHWObject(hwObj); + delete hwObj; + } + + // Call function of base class to remove config + return HWMapper::clrDpPa(dpId, confPtr); +} + +void RAMS7200HWMapper::addAddress(const std::string &ip, const std::string &var, const std::string &pollTime) +{ + auto msIt = RAMS7200MSs.find(ip); + if(msIt == RAMS7200MSs.end()) + { + msIt = RAMS7200MSs.emplace(std::piecewise_construct, + std::forward_as_tuple(ip), + std::forward_as_tuple(RAMS7200MS{ip})).first; + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "New RAMS7200MS device incoming, IP : " + CharString(msIt->second._ip.c_str())); + if(_newMSCB){ + _newMSCB(msIt->second); + } + } + if(!msIt->second._run.load() && _newMSCB){ + _newMSCB(msIt->second); + } + if(Common::S7Utils::AddressIsValid(var)) + msIt->second.addVar(var, std::stoi(pollTime)); +} + + +void RAMS7200HWMapper::removeAddress(const std::string &ip, const std::string &var, const std::string &pollTime) +{ + auto msIt = RAMS7200MSs.find(ip); + if(msIt != RAMS7200MSs.end()) { + { + std::lock_guard lk(msIt->second._threadMutex); + msIt->second._run.store(false); + } + msIt->second._threadCv.notify_all(); + msIt->second.removeVar(var); + if(msIt->second.isEmpty()) { + Common::Logger::globalInfo(Common::Logger::L1, __PRETTY_FUNCTION__, "All Addresses deleted for IP : " + CharString(ip.c_str())); + RAMS7200MSs.erase(msIt); + } + } + +} diff --git a/RAMS7200HWMapper.hxx b/RAMS7200HWMapper.hxx new file mode 100644 index 0000000..e646095 --- /dev/null +++ b/RAMS7200HWMapper.hxx @@ -0,0 +1,56 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + + +#ifndef RAMS7200HWMAPPER_H_ +#define RAMS7200HWMAPPER_H_ + +#include +#include + +#include "RAMS7200MS.hxx" + +#define RAMS7200DrvBoolTransType (TransUserType) +#define RAMS7200DrvUint8TransType (TransUserType + 1) +#define RAMS7200DrvInt16TransType (TransUserType + 2) +#define RAMS7200DrvInt32TransType (TransUserType + 3) +#define RAMS7200DrvFloatTransType (TransUserType + 4) +#define RAMS7200DrvStringTransType (TransUserType + 5) + +using newMSCB = std::function; + +class RAMS7200HWMapper : public HWMapper +{ + public: + virtual PVSSboolean addDpPa(DpIdentifier &dpId, PeriphAddr *confPtr); + virtual PVSSboolean clrDpPa(DpIdentifier &dpId, PeriphAddr *confPtr); + + std::unordered_map& getRAMS7200MSs(){return RAMS7200MSs;} + void setNewMSCallback(newMSCB cb){_newMSCB = cb;} + + private: + void addAddress(const std::string &ip, const std::string &var, const std::string &pollTime); + void removeAddress(const std::string& ip, const std::string& var, const std::string &pollTime); + std::unordered_map RAMS7200MSs; + newMSCB _newMSCB{nullptr}; + + enum Direction + { + DIRECTION_OUT = 1, + DIRECTION_IN = 2, + DIRECTION_INOUT = 6, + }; +}; + +#endif diff --git a/RAMS7200HWService.cxx b/RAMS7200HWService.cxx new file mode 100644 index 0000000..ce0c4d3 --- /dev/null +++ b/RAMS7200HWService.cxx @@ -0,0 +1,272 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * Co-author: Richi Dubey (HSE) + * + **/ + +#include +#include "RAMS7200Resources.hxx" + +#include +#include // DEBUG macros +#include "Common/Logger.hxx" +#include "Common/Constants.hxx" +#include "Common/Utils.hxx" + +#include "RAMS7200HWMapper.hxx" +#include "RAMS7200LibFacade.hxx" + +#include +#include +#include +#include +#include +#include + +static std::atomic _driverRun{true}; + +//-------------------------------------------------------------------------------- +// called after connect to data + +RAMS7200HWService::RAMS7200HWService() +{ + signal(SIGSEGV, handleSegfault); +} + +PVSSboolean RAMS7200HWService::initialize(int argc, char *argv[]) +{ + // use this function to initialize internals + // if you don't need it, you can safely remove the whole method + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"RAMS7200 Driver initialization of Internal vars start"); + + // add callback for new MS + static_cast(DrvManager::getHWMapperPtr())->setNewMSCallback(_newMSCB); + + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"RAMS7200 Driver initialization of Internal vars end"); + // To stop driver return PVSS_FALSE + return PVSS_TRUE; +} + + +void RAMS7200HWService::queueToDP(std::vector&& payload) +{ + std::lock_guard lock{_toDPmutex}; + for(auto& item : payload) + { + _toDPqueue.emplace(std::move(item)); + } +} + +void RAMS7200HWService::handleNewMS(RAMS7200MS& ms) +{ + std::lock_guard lock{_toDPmutex}; + ms._run = true; + + // PLC thread + _plcThreads.emplace_back(std::thread([&]() { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Thread up for PLC IP" + CharString(ms._ip.c_str())); + + RAMS7200LibFacade aFacade(ms, this->_queueToDPCB); + aFacade.Connect(); + bool wasActive = !RAMS7200Resources::getDisableCommands(); + const auto cycleInterval = std::chrono::seconds(Common::Constants::getCycleInterval()); + while(_driverRun && ms._run) + { + const bool isNowActive = !RAMS7200Resources::getDisableCommands(); + aFacade.EnsureConnection(wasActive != isNowActive); + if(isNowActive) { + // The Server is Active (for redundant systems) + Common::Logger::globalInfo(Common::Logger::L2,__PRETTY_FUNCTION__, "Polling:", ms._ip.c_str()); + const auto start = std::chrono::steady_clock::now(); + //First do all the writes for this IP, then the reads + aFacade.WriteToPLC(); + aFacade.Poll(); + const auto end = std::chrono::steady_clock::now(); + const auto time_elapsed = end - start; + + // If we still have time left, then sleep + if(time_elapsed < cycleInterval) + aFacade.sleep_for(cycleInterval- time_elapsed); + } else { + // The Server is Passive (for redundant systems) + aFacade.sleep_for( std::chrono::seconds(1)); + } + wasActive = isNowActive; + } + })); + +} + +//-------------------------------------------------------------------------------- +// called after connect to event + +PVSSboolean RAMS7200HWService::start() +{ + // use this function to start your hardware activity. + // The ms list is automatically built by exisiting addresses sent at driver startup + for (auto& msIt : static_cast(DrvManager::getHWMapperPtr())->getRAMS7200MSs() ) + { + this->handleNewMS(msIt.second); + } + + //Write Driver version + char* DrvVersion = new char[Common::Constants::getDrvVersion().size()+1]; + std::strcpy(DrvVersion, Common::Constants::getDrvVersion().c_str()); + Common::Logger::globalInfo(Common::Logger::L1, __PRETTY_FUNCTION__, "RAMS7200 Sent Driver version: " + CharString(DrvVersion)); + queueToDP({std::make_tuple("_VERSION", Common::Constants::getDrvVersion().size() + 1, DrvVersion)}); + + return PVSS_TRUE; +} + +//-------------------------------------------------------------------------------- + +void RAMS7200HWService::stop() +{ + // use this function to stop your hardware activity. + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__,"RAMS7200 Driver requested to Stop"); + _driverRun.store(false); + + for (auto& msIt : static_cast(DrvManager::getHWMapperPtr())->getRAMS7200MSs() ) + { + msIt.second._run.store(false); + msIt.second._threadCv.notify_all(); + } + + for(auto& pt : _plcThreads) + { + if(pt.joinable()) + pt.join(); + } + +} + +//-------------------------------------------------------------------------------- + +void RAMS7200HWService::workProc() +{ + + HWObject obj; + std::lock_guard lock{_toDPmutex}; + + while (!_toDPqueue.empty()) + { + auto item = std::move(_toDPqueue.front()); + _toDPqueue.pop(); + + obj.setAddress(std::get<0>(item)); + + // find the HWObject via the periphery address in the HWObject list, + HWObject *addrObj = DrvManager::getHWMapperPtr()->findHWObject(&obj); + + // ok, we found it; now send to the DPEs + if ( addrObj ) + { + //addrObj->debugPrint(); + obj.setOrgTime(TimeVar()); // current time + obj.setDlen(std::get<1>(item)); //length + obj.setData((PVSSchar*)(std::move(std::get<2>(item)))); //data + obj.setObjSrcType(srcPolled); + + if( DrvManager::getSelfPtr()->toDp(&obj, addrObj) != PVSS_TRUE) { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "Problem in sending item's value to PVSS for address: " + std::get<0>(item)); + } + } else { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "Problem in getting HWObject for the address: " + std::get<0>(item)); + } + } +} + + +//-------------------------------------------------------------------------------- +// we get data from PVSS and shall send it to the periphery + +PVSSboolean RAMS7200HWService::writeData(HWObject *objPtr) +{ + Common::Logger::globalInfo(Common::Logger::L2,__PRETTY_FUNCTION__,"Incoming obj address",objPtr->getAddress()); + + std::vector addressOptions = Common::Utils::split(objPtr->getAddress().c_str()); + + // CONFIG DPs have just 1 + if(addressOptions.size() == 1) + { + try + { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Incoming CONFIG address" + CharString(objPtr->getAddress()) + " : " +CharString(objPtr->getInfo()) ); + Common::Constants::GetParseMap().at(std::string(objPtr->getAddress().c_str()))((const char*)objPtr->getData()); + } + catch (std::exception& e) + { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "No configuration handling for address:", CharString(objPtr->getAddress().c_str()) + ':' + CharString(e.what())); + } + } + else if (addressOptions.size() == ADDRESS_OPTIONS_SIZE) // Send to PLC + { + + if(!addressOptions[ADDRESS_OPTIONS_IP].length()) + { + Common::Logger::globalWarning(__PRETTY_FUNCTION__,"Empty IP"); + return PVSS_FALSE; + } + + if(!Common::S7Utils::AddressIsValid(addressOptions[ADDRESS_OPTIONS_VAR])){ + Common::Logger::globalWarning("Not a valid Var for address", objPtr->getAddress().c_str()); + return PVSS_FALSE; + } + + auto& mss = static_cast(DrvManager::getHWMapperPtr())->getRAMS7200MSs(); + auto msIt = mss.find(addressOptions[ADDRESS_OPTIONS_IP]); + if(msIt == mss.end()){ + Common::Logger::globalWarning(__PRETTY_FUNCTION__,"Connection not found for IP: ", addressOptions[ADDRESS_OPTIONS_IP].c_str()); + return PVSS_FALSE; + } + + const auto length = static_cast(objPtr->getDlen()); + auto correctval = new char[length]; + std::memcpy(correctval, objPtr->getDataPtr(), length); + + if(length == 2) { + int16_t inInt16 = Common::Utils::CopyNSwapBytes(correctval); + Common::Logger::globalInfo(Common::Logger::L2, "Received request to write integer, Correct val is: ", std::to_string(inInt16).c_str()); + } else if(length == 4){ + float inFloat = Common::Utils::CopyNSwapBytes(correctval); + Common::Logger::globalInfo(Common::Logger::L2, "Received request to write float, Correct val is: ", std::to_string(inFloat).c_str()); + } else { + Common::Logger::globalInfo(Common::Logger::L2, "Received request to write non integer/float: ", reinterpret_cast(correctval), reinterpret_cast(correctval) + length); + } + + msIt->second.queuePLCItem(addressOptions[ADDRESS_OPTIONS_VAR], correctval); + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Added write request to queue for Address: " + CharString(objPtr->getAddress()) + " : "+ CharString(objPtr->getInfo()) ); + } + else + { + Common::Logger::globalWarning(__PRETTY_FUNCTION__," Invalid address options size for address: ", objPtr->getAddress().c_str()); + } + + return PVSS_TRUE; +} + +//-------------------------------------------------------------------------------- +void handleSegfault(int signal_code){ + void *array[50]; + size_t size; + + // get void*'s for all entries on the stack + size = backtrace(array, 50); + + // print out all the frames to stderr + fprintf( stderr, "Error: signal %d:\n", signal_code); + Common::Logger::globalWarning("RAMS7200HWService suffered a segmentation fault, code " + CharString(signal_code)); + backtrace_symbols_fd(array, size, STDERR_FILENO); + + // restore and trigger default handle (to get the core dump) + signal(signal_code, SIG_DFL); +} diff --git a/RAMS7200HWService.hxx b/RAMS7200HWService.hxx new file mode 100644 index 0000000..e13180b --- /dev/null +++ b/RAMS7200HWService.hxx @@ -0,0 +1,67 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + + +#ifndef RAMS7200HWSERVICE_H_ +#define RAMS7200HWSERVICE_H_ + +#include +#include "RAMS7200MS.hxx" +#include "RAMS7200LibFacade.hxx" +#include "Common/Logger.hxx" + +#include +#include +#include +#include +#include +#include + +class RAMS7200HWService : public HWService +{ + public: + RAMS7200HWService(); + virtual PVSSboolean initialize(int argc, char *argv[]); + virtual PVSSboolean start(); + virtual void stop(); + virtual void workProc(); + virtual PVSSboolean writeData(HWObject *objPtr); + int CheckIP(std::string); + + private: + void queueToDP(std::vector&&); + void handleNewMS(RAMS7200MS&); + + queueToDPCallback _queueToDPCB{[this](std::vector&& payload){this->queueToDP(std::move(payload));}}; + std::function _newMSCB{[this](RAMS7200MS& ms){this->handleNewMS(ms);}}; + + //Common + std::mutex _toDPmutex; + std::queue _toDPqueue; + + enum + { + ADDRESS_OPTIONS_IP = 0, + ADDRESS_OPTIONS_VAR, + ADDRESS_OPTIONS_POLLTIME, + ADDRESS_OPTIONS_SIZE + } ADDRESS_OPTIONS; + + std::vector _plcThreads; +}; + + +void handleSegfault(int signal_code); + +#endif diff --git a/RAMS7200LibFacade.cxx b/RAMS7200LibFacade.cxx new file mode 100644 index 0000000..df56033 --- /dev/null +++ b/RAMS7200LibFacade.cxx @@ -0,0 +1,291 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200LibFacade.hxx" +#include "RAMS7200Resources.hxx" +#include "Common/Constants.hxx" +#include "Common/Logger.hxx" +#include +#include +#include +#include +#include + + +RAMS7200LibFacade::RAMS7200LibFacade(RAMS7200MS& ms, queueToDPCallback cb) + : ms(ms), _queueToDPCB(cb) +{ + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Initialized LibFacade with PLC IP: "+ CharString(ms._ip.c_str())); +} + + +void RAMS7200LibFacade::EnsureConnection(bool reduSwitch) { + + if(reduSwitch) { + RAMS7200MarkDeviceConnectionError(!_client->Connected()); + } + if(_client->Connected() && ioFailures < Common::Constants::getMaxIoFailures()){ + return; + } else { + if (_wasConnected) { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Snap7: Connection lost with PLC IP: ", ms._ip.c_str()); + RAMS7200MarkDeviceConnectionError(true); + } + do { + //Disconnect and try to connect again. + Disconnect(); + Connect(); + + if(!_client->Connected()) { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Failure in re-connection. Trying again in 5 seconds for PLC IP:" + CharString(ms._ip.c_str())); + sleep_for(std::chrono::seconds(5)); + } + } while(ms._run && !_wasConnected); + RAMS7200MarkDeviceConnectionError(false); + } +} + +void RAMS7200LibFacade::Connect() +{ + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Snap7: Connecting to : Local TSAP Port : Remote TSAP Port'", (ms._ip + " : "+ std::to_string(Common::Constants::getLocalTsapPort()) + ":" + std::to_string(Common::Constants::getRemoteTsapPort())).c_str()); + + _client.reset(new TS7Client()); + + _client->SetConnectionParams(ms._ip.c_str(), Common::Constants::getLocalTsapPort(), Common::Constants::getRemoteTsapPort()); + if(_client->Connect() == 0) { + _wasConnected = true; + } + RAMS7200MarkDeviceConnectionError(!_client->Connected()); +} + + +void RAMS7200LibFacade::Disconnect() +{ + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, "Snap7: Disconnecting from '", ms._ip.c_str()); + _client->Disconnect(); + _wasConnected = false; + ioFailures = 0; +} + + +void RAMS7200LibFacade::Poll() +{ + if(ms.vars.empty()){ + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "No addresses for PLC IP:", ms._ip.c_str()); + return; + } + auto pollStartTime = std::chrono::steady_clock::now(); + Common::Logger::globalInfo(Common::Logger::L3,__PRETTY_FUNCTION__, ms._ip.c_str()); + std::vector addressesToPoll; + std::vector items; + const auto pollInterval = Common::Constants::getPollingInterval(); + { + std::lock_guard lock{ms._rwmutex}; + for(auto& [_, var] : ms.vars) { + const auto fpollTime = var.pollTime > pollInterval ? var.pollTime : pollInterval; + const auto tDiff = std::chrono::duration_cast(pollStartTime - var.lastPollTime).count(); + if(tDiff >= fpollTime) { + var.lastPollTime = std::chrono::steady_clock::now(); + addressesToPoll.emplace_back(DPInfo{ + dpAddress: ms._ip + "$" + var.varName + "$" + std::to_string(var.pollTime), + plcAddress: var.varName, + dpSize: Common::S7Utils::GetByteSizeFromAddress(var.varName), + }); + items.emplace_back(Common::S7Utils::TS7DataItemShallowClone(var._toDP)); + } + } + } + if(!addressesToPoll.empty()) { + RAMS7200ReadWriteMaxN(addressesToPoll, items, 19, PDU_SIZE, OVERHEAD_READ_VARIABLE, OVERHEAD_READ_MESSAGE, Common::S7Utils::Operation::READ); + } + else + { + Common::Logger::globalInfo(Common::Logger::L3, "No vars to poll at the moment"); + } + +} + +void RAMS7200LibFacade::WriteToPLC() { + std::vector addresses; + std::vector items; + { + std::lock_guard lock{ms._rwmutex}; + for(auto& [_, var] : ms.vars) { + if(var._toPlc.pdata != nullptr){ + addresses.emplace_back(DPInfo{ + dpAddress: ms._ip + "$" + var.varName + "$" + std::to_string(var.pollTime), + plcAddress: var.varName, + dpSize: Common::S7Utils::GetByteSizeFromAddress(var.varName), + }); + items.emplace_back(var._toPlc); + var._toPlc.pdata = nullptr; + // Make sure that the next poll will happen immediately + var.lastPollTime -= std::chrono::seconds(std::max(var.pollTime, Common::Constants::getPollingInterval())); + } + } + } + if(!addresses.empty()){ + RAMS7200ReadWriteMaxN(addresses, items, 10, PDU_SIZE, OVERHEAD_WRITE_VARIABLE, OVERHEAD_WRITE_MESSAGE, Common::S7Utils::Operation::WRITE); + } + else + { + Common::Logger::globalInfo(Common::Logger::L3, "No vars to write at the moment"); + } +} + + +void RAMS7200LibFacade::RAMS7200MarkDeviceConnectionError(bool error_status){ + if (!RAMS7200Resources::getDisableCommands()) { + Common::Logger::globalInfo(Common::Logger::L1,__PRETTY_FUNCTION__, std::to_string(error_status).c_str(), CharString("PLC IP: ") + CharString(ms._ip.c_str())) ; + auto pdata = new char[sizeof(bool)]; + memcpy(pdata, &error_status , sizeof(bool)); + this->_queueToDPCB({std::make_tuple(ms._ip + "._system$_Error",sizeof(bool), pdata)}); + } +} + +void RAMS7200LibFacade::RAMS7200ReadWriteMaxN(std::vector dpItems, std::vector items, const uint N, const int PDU_SZ, const int VAR_OH, const int MSG_OH, const Common::S7Utils::Operation rorw) { + try{ + + int retOpt; + int curr_sum; + uint last_index = 0; + uint to_send = 0; + while(last_index < items.size()) { + if(ioFailures >= Common::Constants::getMaxIoFailures()) { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "Max IO Failures reached for PLC IP:", ms._ip.c_str()); + break; + } + to_send = 0; + curr_sum = 0; + + for (auto it = items.begin() + last_index; it != items.end(); ++it) { + const auto& var = *it; + const auto dataSize = Common::S7Utils::DataSizeByte(var.WordLen) * var.Amount; + const auto itemSize = dataSize + VAR_OH; + if (curr_sum + itemSize < PDU_SZ - MSG_OH && to_send < N) { + curr_sum += itemSize; + ++to_send; + } else { + break; + } + } + + if(to_send == 0) { + //This means that the current variable has a mem size > PDU. Call with ReadArea because it can split the request automatically (PDU Independance) + to_send += 1; + const auto& last_item = items[last_index]; + curr_sum = ((Common::S7Utils::DataSizeByte(last_item.WordLen)) * last_item.Amount) + VAR_OH + MSG_OH; + + if(rorw == Common::S7Utils::Operation::READ) + retOpt = _client->ReadArea(last_item.Area, last_item.DBNumber, last_item.Start, last_item.Amount, last_item.WordLen, last_item.pdata); + else + retOpt = _client->WriteArea(last_item.Area, last_item.DBNumber, last_item.Start, last_item.Amount, last_item.WordLen, last_item.pdata); + + } else { + if(rorw == Common::S7Utils::Operation::READ) + retOpt = _client->ReadMultiVars(&(items[last_index]), to_send); + else { + retOpt = _client->WriteMultiVars(&(items[last_index]), to_send); + } + } + + if( retOpt != 0) { + ++ioFailures; + for(auto i = last_index; i < last_index + to_send; i++) { + items[i].Result = retOpt; + } + std::stringstream ss; + ss << ms._ip << (rorw == Common::S7Utils::Operation::READ ? "Read" : "Write"); + ss << " KO for PLC IP:" << ms._ip << " with " << to_send << " items and PDU size of " << curr_sum + MSG_OH << " bytes , ioFailures: " << ioFailures; + Common::Logger::globalWarning(ss.str().c_str()); + } + last_index += to_send; + } + if(rorw == Common::S7Utils::Operation::READ) { + if(Common::Constants::getSmoothing()) { + doSmoothing(std::move(dpItems), std::move(items)); + } else { + queueAll(std::move(dpItems), std::move(items)); + } + } + + } + catch(std::exception& e){ + Common::Logger::globalWarning(__PRETTY_FUNCTION__," Encountered Exception:", e.what()); + } +} + +void RAMS7200LibFacade::queueAll(std::vector&& dpItems, std::vector&& s7items){ + + std::vector toDPItems; + toDPItems.reserve(s7items.size()); + + std::stringstream failed; + + for(uint i = 0; i < s7items.size(); i++) { + if(s7items[i].Result == 0) { + Common::Logger::globalInfo(Common::Logger::L4, dpItems[i].dpAddress.c_str(), Common::S7Utils::DisplayTS7DataItem(&s7items[i], Common::S7Utils::Operation::READ).c_str()); + toDPItems.emplace_back(dpItems[i].dpAddress.c_str(), dpItems[i].dpSize, static_cast(s7items[i].pdata)); + } else { + failed << dpItems[i].dpAddress.c_str() << " "; + delete[] static_cast(s7items[i].pdata); + } + } + + if (!failed.str().empty()) { + Common::Logger::globalWarning("Failed for: ", failed.str().c_str()); + } + + _queueToDPCB(std::move(toDPItems)); +} + +void RAMS7200LibFacade::doSmoothing(std::vector&& dpItems, std::vector&& s7items){ + + std::vector toDPItems; + toDPItems.reserve(s7items.size()); + + std::stringstream failed; + + { + std::lock_guard lock(ms._rwmutex); + + for(uint i = 0; i < s7items.size(); i++) { + if(auto item = s7items[i]; item.Result == 0) { + const auto& DPInfo = dpItems[i]; + Common::Logger::globalInfo(Common::Logger::L4, DPInfo.dpAddress.c_str(), Common::S7Utils::DisplayTS7DataItem(&item, Common::S7Utils::Operation::READ).c_str()); + auto it = ms.vars.find(DPInfo.plcAddress); + if(it != ms.vars.end()) { + auto& var = it->second; + const auto dataSize = var._toDP.Amount * Common::S7Utils::DataSizeByte(var._toDP.WordLen); + if (std::memcmp(var._toDP.pdata, item.pdata, dataSize) != 0) { + std::memcpy(var._toDP.pdata, item.pdata, dataSize); + toDPItems.emplace_back(DPInfo.dpAddress.c_str(), dataSize, static_cast(item.pdata)); + Common::Logger::globalInfo(Common::Logger::L4, DPInfo.dpAddress.c_str(), "--> Smoothing updated"); + continue; + } + } + } else { + failed << dpItems[i].dpAddress.c_str() << " "; + } + delete[] static_cast(s7items[i].pdata); + } + } + + if (!failed.str().empty()) { + Common::Logger::globalWarning("Failed for: ", failed.str().c_str()); + } + _queueToDPCB(std::move(toDPItems)); +} \ No newline at end of file diff --git a/RAMS7200LibFacade.hxx b/RAMS7200LibFacade.hxx new file mode 100644 index 0000000..378f307 --- /dev/null +++ b/RAMS7200LibFacade.hxx @@ -0,0 +1,98 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200LIBFACADE_HXX +#define RAMS7200LIBFACADE_HXX + +#define OVERHEAD_READ_MESSAGE 13 +#define OVERHEAD_READ_VARIABLE 5 +#define OVERHEAD_WRITE_MESSAGE 12 +#define OVERHEAD_WRITE_VARIABLE 16 +#define PDU_SIZE 240 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "RAMS7200MS.hxx" +#include "Common/Logger.hxx" + + +/** + * @brief The RAMS7200LibFacade class is a facade and encompasses all the consumer interaction with snap7 + */ + +class RAMS7200LibFacade +{ +public: + /** + * @brief RAMS7200LibFacade constructor + * @param RAMS7200MS & : const reference to the MS object + * @param queueToDPCallback : a callback that will be called after each poll + * */ + RAMS7200LibFacade(RAMS7200MS& , queueToDPCallback); + + + RAMS7200LibFacade(const RAMS7200LibFacade&) = delete; + RAMS7200LibFacade& operator=(const RAMS7200LibFacade&) = delete; + RAMS7200LibFacade(RAMS7200LibFacade&&) = delete; + RAMS7200LibFacade& operator=(RAMS7200LibFacade&&) = delete; + ~RAMS7200LibFacade() = default; + + void Poll(); + void WriteToPLC(); + void EnsureConnection(bool reduSwitch); + + void Connect(); + + template + void sleep_for(T duration) + { + std::unique_lock lk(ms._threadMutex); + ms._threadCv.wait_for(lk, duration, [&](){ + return !ms._run.load(); + }); + } + +private: + void Reconnect(); + void Disconnect(); + void RAMS7200MarkDeviceConnectionError(bool); + void RAMS7200ReadWriteMaxN(std::vector dpItems, std::vector items, const uint N, const int PDU_SZ, const int VAR_OH, const int MSG_OH, const Common::S7Utils::Operation rorw); + void doSmoothing(std::vector&& dpItems, std::vector&& items); + void queueAll(std::vector&& dpItems, std::vector&& items); + + uint32_t ioFailures{0}; + RAMS7200MS& ms; + + // S7 related + queueToDPCallback _queueToDPCB; + bool _wasConnected{false}; + std::unique_ptr _client{nullptr}; +}; + +#endif //RAMS7200LIBFACADE_HXX + diff --git a/RAMS7200MS.cxx b/RAMS7200MS.cxx new file mode 100644 index 0000000..a4a5381 --- /dev/null +++ b/RAMS7200MS.cxx @@ -0,0 +1,61 @@ +/** © Copyright 2023 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Alexandru Savulescu (HSE) + * + **/ + +#include "RAMS7200MS.hxx" +#include "Common/S7Utils.hxx" +#include "Common/Logger.hxx" +#include + + +RAMS7200MSVar::RAMS7200MSVar(std::string varName, int pollTime, TS7DataItem type) : varName(varName), pollTime(pollTime), _toPlc(type), _toDP(type) +{ + if(Common::Constants::getSmoothing()){ + Common::S7Utils::TS7AllocateDataItemForAddress(_toDP); + } +} + +void RAMS7200MS::addVar(std::string varName, int pollTime) +{ + std::lock_guard lock{_rwmutex}; + auto var = RAMS7200MSVar(varName, pollTime, Common::S7Utils::TS7DataItemFromAddress(varName, false)); + vars.emplace(varName, std::move(var)); +} + +void RAMS7200MS::removeVar(std::string varName) +{ + std::lock_guard lock{_rwmutex}; + auto it = vars.find(varName); + if(it != vars.end()) { + if (it->second._toDP.pdata != nullptr) { + delete[] static_cast(it->second._toDP.pdata); + } + if (it->second._toPlc.pdata != nullptr) { + delete[] static_cast(it->second._toPlc.pdata); + } + vars.erase(it); + } +} + +void RAMS7200MS::queuePLCItem(const std::string& varName, void* item) +{ + try + { + std::lock_guard lock{_rwmutex}; + vars.at(varName)._toPlc.pdata = item; + } + catch(const std::out_of_range& e) + { + Common::Logger::globalWarning(__PRETTY_FUNCTION__, "Undefined address", e.what()); + } +} diff --git a/RAMS7200MS.hxx b/RAMS7200MS.hxx new file mode 100644 index 0000000..98a85fa --- /dev/null +++ b/RAMS7200MS.hxx @@ -0,0 +1,85 @@ +/** © Copyright 2023 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Alexandru Savulescu (HSE) + * + **/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include "Common/S7Utils.hxx" +#include "Common/Constants.hxx" +#include +#include "CharString.hxx" + +using toDPTriple = std::tuple; +using queueToDPCallback = std::function&&)>; + +struct RAMS7200MSVar +{ + RAMS7200MSVar(std::string varName, int pollTime, TS7DataItem type); + + const std::string varName; + const uint32_t pollTime; + std::chrono::steady_clock::time_point lastPollTime{std::chrono::steady_clock::now()}; + TS7DataItem _toPlc; + TS7DataItem _toDP; + bool _isString{false}; + +}; + +struct DPInfo +{ + // DP info + const std::string dpAddress; + const std::string plcAddress; + const int dpSize; +}; + +class RAMS7200MS +{ + public: + RAMS7200MS() = delete; + RAMS7200MS(std::string ip): _ip(ip) {}; + RAMS7200MS(const RAMS7200MS&) = delete; + RAMS7200MS& operator=(const RAMS7200MS&) = delete; + RAMS7200MS(RAMS7200MS&& other) noexcept : _ip(other._ip) { + if(this == &other) return; + vars = std::move(other.vars); + _run = other._run.load(); + } + RAMS7200MS& operator=(RAMS7200MS&& other) = delete; + ~RAMS7200MS() = default; + protected: + void addVar(std::string varName, int pollTime); + void removeVar(std::string varName); + const std::string _ip; + + void queuePLCItem(const std::string& varName, void* item); + inline bool isEmpty() const {return vars.empty();} + private: + std::unordered_map vars; + std::atomic _run{false}; + std::mutex _rwmutex; + bool previouslyConnected{false}; + std::mutex _threadMutex; + std::condition_variable _threadCv; + + friend class RAMS7200LibFacade; + friend class RAMS7200HWService; + friend class RAMS7200HWMapper; +}; diff --git a/RAMS7200Main.cxx b/RAMS7200Main.cxx new file mode 100644 index 0000000..60dd1aa --- /dev/null +++ b/RAMS7200Main.cxx @@ -0,0 +1,75 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include +#include +#include "Common/Logger.hxx" +#include "Common/Constants.hxx" + +#include +#include + +int main(int argc, char **argv) +{ + // an instance of our own Resources class is needed + RAMS7200Resources& resources = RAMS7200Resources::GetInstance(); + + resources.init(argc, argv); + + RAMS7200Resources::setDriverType(Common::Constants::getDrvName().c_str()); + + // the user wants to know std. commandline options + if ( resources.getHelpFlag() ) + { + resources.printHelp(); + return 0; + } + + // the user wants to know std. debug flags + if ( resources.getHelpDbgFlag() ) + { + resources.printHelpDbg(); + return 0; + } + + // the user wants to know std. report flags + if ( resources.getHelpReportFlag() ) + { + resources.printHelpReport(); + return 0; + } + + RAMS7200Drv *driver = nullptr; + + try{ + // handle std. signals + signal(SIGINT, Manager::sigHdl); + signal(SIGTERM, Manager::sigHdl); + + // a pointer is needed, since the Manager dtor does a delete + RAMS7200Drv *driver = new RAMS7200Drv; + + driver->mainProcedure(argc, argv); + + return 0; + } + catch(std::exception& e){ + Common::Logger::globalWarning("Exception"); + if(driver) + driver->exit(0); + Common::Logger::globalError(e.what()); + } + return 0; + +} diff --git a/RAMS7200Resources.cxx b/RAMS7200Resources.cxx new file mode 100644 index 0000000..7a22a04 --- /dev/null +++ b/RAMS7200Resources.cxx @@ -0,0 +1,116 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +// Our Resource class. +// This class will interpret the command line and read the config file + +#include "RAMS7200Resources.hxx" +#include "Common/Logger.hxx" +#include "Common/Constants.hxx" +#include + +const CharString RAMS7200Resources::SECTION_NAME = "rams7200"; +const CharString RAMS7200Resources::TSAP_PORT_LOCAL = "localTSAP"; +const CharString RAMS7200Resources::TSAP_PORT_REMOTE = "remoteTSAP"; +const CharString RAMS7200Resources::POLLING_INTERVAL = "pollingInterval"; +const CharString RAMS7200Resources::SMOOTHING = "smoothing"; +const CharString RAMS7200Resources::MAX_IO_FAILURES = "maxIoFailures"; +const CharString RAMS7200Resources::CYCLE_INTERVAL = "cycleInterval"; + +//------------------------------------------------------------------------------- +// init is a wrapper around begin, readSection and end + +void RAMS7200Resources::init(int &argc, char *argv[]) +{ + // Prepass of commandline arguments, e.g. get the arguments needed to + // find the config file. + begin(argc, argv); + + // Read the config file + while ( readSection() || generalSection() ) ; + + // Postpass of the commandline arguments, e.g. get the arguments that + // will override entries in the config file + end(argc, argv); +} + +//------------------------------------------------------------------------------- + +PVSSboolean RAMS7200Resources::readSection() { + // Are we in our section ? This is true for "remus_drv" or "remus_drv_" + if (!isSection(SECTION_NAME)) + return PVSS_FALSE; + + // skip "[remus_drv_]" + getNextEntry(); + + std::string tmpStr; + + try{ + // Now read the section until new section or end of file + while ((cfgState != CFG_SECT_START) && (cfgState != CFG_EOF)) { + // Test the keywords + if (keyWord.startsWith(TSAP_PORT_LOCAL)) { + cfgStream >> tmpStr; + Common::Constants::setLocalTsapPort(strtol(tmpStr.c_str(), NULL, 16)); + }else if(keyWord.startsWith(TSAP_PORT_REMOTE)) { + cfgStream >> tmpStr; + Common::Constants::setRemoteTsapPort(strtol(tmpStr.c_str(), NULL, 16)); + }else if(keyWord.startsWith(POLLING_INTERVAL)) { + cfgStream >> tmpStr; + Common::Constants::setPollingInterval(atoi(tmpStr.c_str())); + }else if(keyWord.startsWith(SMOOTHING)) { + cfgStream >> tmpStr; + // boolean value + Common::Constants::setSmoothing(atoi(tmpStr.c_str())); + }else if(keyWord.startsWith(MAX_IO_FAILURES)) { + cfgStream >> tmpStr; + Common::Constants::setMaxIoFailures(atoi(tmpStr.c_str())); + }else if(keyWord.startsWith(CYCLE_INTERVAL)) { + cfgStream >> tmpStr; + Common::Constants::setCycleInterval(atoi(tmpStr.c_str())); + }else{ + // Unknown keyword + Common::Logger::globalWarning("Unknown keyword in config file: ", keyWord.c_str()); + } + + getNextEntry(); + } + }catch(std::runtime_error& e){ + Common::Logger::globalError(e.what()); + return PVSS_FALSE; + } + + // So the loop will stop at the end of the file + return cfgState != CFG_EOF; +} + + +RAMS7200Resources& RAMS7200Resources::GetInstance() +{ + static RAMS7200Resources krs; + return krs; +} + +//------------------------------------------------------------------------------- +// Interface to internal Datapoints +// Get the number of names we need the DpId for + +int RAMS7200Resources::getNumberOfDpNames() +{ + // TODO if you use internal DPs + return 0; +} + +//------------------------------------------------------------------------------- diff --git a/RAMS7200Resources.hxx b/RAMS7200Resources.hxx new file mode 100644 index 0000000..bcbdb6e --- /dev/null +++ b/RAMS7200Resources.hxx @@ -0,0 +1,52 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200RESOURCES_H_ +#define RAMS7200RESOURCES_H_ + +// Our Resources class +// This class has two tasks: +// - Interpret commandline and read config file +// - Be an interface to internal datapoints + +#include + +class RAMS7200Resources : public DrvRsrce +{ + public: + + static void init(int &argc, char *argv[]); // Initialize statics + static PVSSboolean readSection(); // read config file + static RAMS7200Resources& GetInstance(); + + // Get the number of names we need the DpId for + virtual int getNumberOfDpNames(); + + // TODO in this template we do not use internal DPs in the driver + // If you need DPs, then also some other methods must be implemented + RAMS7200Resources(RAMS7200Resources const&) = delete; + void operator= (RAMS7200Resources const&) = delete; + private: + RAMS7200Resources(){} + + static const CharString SECTION_NAME; + static const CharString TSAP_PORT_LOCAL; + static const CharString TSAP_PORT_REMOTE; + static const CharString POLLING_INTERVAL; + static const CharString SMOOTHING; + static const CharString MAX_IO_FAILURES; + static const CharString CYCLE_INTERVAL; +}; + +#endif diff --git a/README.md b/README.md new file mode 100644 index 0000000..71977dc --- /dev/null +++ b/README.md @@ -0,0 +1,268 @@ +CERN HSE Computing (HSE-TS-CS) +================================================== + +Contact email: hse-ts-cs@cern.ch + +WinCC OA RAMS7200 Driver +================================================== + + +# Table of contents # +1. [Description](#toc1) +2. [Libraries](#toc2) + +3. [Compilation](#toc3) + + 3.1. [To build the driver](#toc3.1) + + 3.2. [Build options](#toc3.2) + + 3.3. [To install and update](#toc3.3) + + 3.4. [Run](#toc3.4) + +4. [Config file](#toc4) + +5. [WinCC OA Installation](#toc5) + +6. [RAMS7200 Driver Technical Documentation](#toc6) + + 6.1. [Main entry points](#toc6.1) + + 6.2. [Addressing DPEs with the RAMS7200 driverl](#toc6.2) + + * 6.2.1 [Data types](#toc6.2.1) + * 6.2.2 [Adding a new type](#toc6.2.4) + + 6.3 [Driver configuration](#toc6.3) + + 6.4 [Activity diagram](#toc6.4) + + + + +# 1. Description # + +This WinCC OA driver enables bidirectional data transfer between RAMS7200 devices and the WinCCOA environment, with support for multiple polling intervals and consolidated write functions. + +Additionally, the driver offers compatibility with multiple IP addresses, making it a versatile and reliable tool for data integration. + + + + +# 2. Libraries # + +* C++11 STL +* WinCC OA API libraries +* Snap7 Library + + + +# 3. Compilation: +The project is CMake enabled. +Note that if you set the `PVSS_PROJ_PATH` environment variable beforehand, you can install and update the driver via the `install` and `update` targets. + + + +## 3.1 To build the driver + + export PVSS_PROJ_PATH= + mkdir build + cd build + cmake .. + make -j + + + +## 3.2 Build options + +The default CMake build type is `Release`. The follow build types are taken into account: + +| Build Type | Details | +|------------|----------------------------------| +| Release | Default, 03 optimization | +| Debug | gdb enabled, no optimization | +| Coverage | gcov enabled, no optimization | +------------------------------------------------- + +To enable a specific build type, run: + + cmake -DCMAKE_BUILD_TYPE= .. + +For Code Coverage make sure you have `lcov` installed. At the end of your tests, perform the following to get the html coverage report: + + make coverage + +If `valgrind` is installed, you can also run the tests with valgrind: + + make valgrind +Once you are done with the tests, you can stop the valgrind process with: + + make kill + + + + +## 3.3 To install and update + +In order to install the driver in the `PVSS_PROJ_PATH/bin`, run: + + make install + +Making changes to the driver and updating it are simplified by using the `update` target, triggering a `clean`, `install` (and `kill` the driver): + + make update + +The `kill` target will simply terminate the running process. Combined with the `always` setting of the driver in WinCCOA, this will ensure that the driver is always up to date. + + + +## 3.3 Run + +It can be run from the WinCCOA Console or from command line and it will require the `config.rams7200` driver_config_file: + + ./WINCCOARAMS7200Drv -num -proj +config + +If you want to run the driver from the `build` folder (i.e. debug, coverage or valgrind mode) you can call: + + make run + +CMake will extract/parse the following information: + +| Variable | Details | +|-----------------------|-------------------------------------------------------------------------------| +| project_name | The PVSS project name from PVSS_PROJ_PATH environment variable | +| driver_number | The driver number from the $PVSS_PROJ_PATH/config/progs file. Defaults to 999.| +| driver_config_file | The driver config file from the $PVSS_PROJ_PATH/config/progs file. | + + + + + + +# 4. Config file # + +The `config.rams7200` file has to be present under the WinCCOA project folder `config`. + +When configuring the file, it is necessary to specify the local and remote TSAP ports, as well as the minimum polling interval required for seamless communication between the WinCCOA environment and external devices or systems. You can also provide the directory for storing the measurement and event files as well as the location of the User file. + +Here is an example config file: +``` +[ramS7200] +# Define local TSAP port +localTSAP = 0x1401 + +# Define remote TSAP port +remoteTSAP = 0x1400 + +# Define polling Interval +pollingInterval = 10 + +# Disable/Enable smoothing +smoothing = 1 + +# Set cycle interval +cycleInterval = 1 + +# Set max number of IO failures before disconnecting and connecting again +maxIoFailures = 5 +``` + + + +# 5. WinCC OA Installation # + +Under the [winccoa folder](./winccoa/) you will find the following files that you need to copy to your project in the corresponding paths: + +* [dplist/rams7200_driver_config.dpl](./winccoa/dplist/rams7200_driver_config.dpl) : it contains `internal driver & CONFIG_RAMS7200 DPs`. Once you've successfully launched the driver in the WinCC project manangement, you can import it via the ASCII Manager(refer to the official WinCC OA Documentation). + +Notes: + + * The internal driver number in the dump is 32. If it's unavailable to you, try to modify the dump file directly and the library file. + +* [dplist/panels/para/address_rams7200.pnl](./winccoa/panels/para/address_rams7200.pnl) : a panel that you can use in para for RAMS7200 addressing. If you install this panel, then you will also need the WinCC OA scripts that go along: + + * [scripts/userDrivers.ctl](./winccoa/scripts/userDrivers.ctl) + * [scripts/userPara.ctl](./winccoa/scripts/userPara.ctl) + +In order to set up the addressing of kafka DPE form a control script, you may use the folowing library: + * [scripts/libs/rams7200_dpe_addressing.ctl](./winccoa/scripts/libs/kafka_dpe_addressing.ctl). + +See [6.3 Driver configuration](#toc6.3) section for a brief descprition of relevant CONFIG_RAMS7200 DPEs. + + + + +# 6. RAMS7200 Driver Technical Documentation # + + + +## 6.1 Main entry points ## +After the driver startup, the main entry points in the driver are: + +* RAMS7200HwService::writeData() -> WinCC to Driver communication + + Addressing is following: `$
$` + +* RAMS7200HwService::workProc() -> Driver to WinCC communication + + This is how we push data to WinCC from RAMS7200. + +Please refer to the WinCC documentation for more information on the WinCC OA API. + + + + +## 6.2 Addressing DPEs with the RAMS7200 driver ## + + + +### 6.2.1 Data Types ### +When the RAMS7200 driver pushes a DPE value to WinCC, a transformation takes place. See [Transformations folder](./Transformations). We are currently supporting the following data types for the periphery address: + +--------------------------------------------------------------------------------------------------------------------------------------- +| WinCC DataType | Transformation class | Periphery data type value | +| ------------------| --------------------------------------------------------------------| ----------------------------------------- | +| bool | [RAMS7200BoolTrans.cxx](./Transformations/RAMS7200BoolTrans.cxx) | 1000 (TransUserType def in WinCC OA API) | +| uint8 | [RAMS7200Uint8Trans.cxx](./Transformations/RAMS7200Uint8Trans.cxx) | 1001 (TransUserType + 1) | +| int16 | [RAMS7200Int16Trans.cxx](./Transformations/RAMS7200Int16Trans.cxx) | 1002 (TransUserType + 2) | +| int32 | [RAMS7200Int32Trans.cxx](./Transformations/RAMS7200Int32Trans.cxx) | 1003 (TransUserType + 3) | +| float | [RAMS7200FloatTrans.cxx](./Transformations/RAMS7200FloatTrans.cxx) | 1004 (TransUserType + 4) | +| string | [RAMS7200StringTrans.cxx](./Transformations/RAMS7200StringTrans.cxx)| 1005 (TransUserType + 5) | +--------------------------------------------------------------------------------------------------------------------------------------- + + + +### 6.2.2 Adding a new transformation ### + +To add a new transformation you need to do the following: + +* create a define in `RAMS7200HWMappeer.hxx` + + #define RAMS7200DrvDoubleTransType (TransUserType + 7) + +* handle the new transformation type in `RAMS7200HWMapper::addDpPa()` +* implement the transformation type class. The important functions here are + + * `::toPeriph(...)` for WinCC OA to RAMS7200 driver transformation + * `::toVar(...)` for RAMS7200 driver to WinCC OA transformation + + + + +## 6.3 Driver Configuration ## + +Available via the WinCC OA `CONFIG_RAMS7200` DataPoint, we have the following + +| Config DPE | Direction | Addressing | Type | Description | +| ------------- | --------- | ------------- | --------- | ------------- | +| DebugLvl | OUT | _DEBUGLVL | INT32 | Debug Level for logging. You can use this to debug issues. (default 1) | +| Driver Version | IN | _VERSION | STRING | The driver version | + + + + + +## 6.4 Activity Diagram ## + +![](./doc/RAMS7200Design.svg) diff --git a/Transformations/RAMS7200BoolTrans.cxx b/Transformations/RAMS7200BoolTrans.cxx new file mode 100644 index 0000000..7bc5ac0 --- /dev/null +++ b/Transformations/RAMS7200BoolTrans.cxx @@ -0,0 +1,83 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200BoolTrans.hxx" + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" + +#include + +#include "BitVar.hxx" + +namespace Transformations{ + +TransformationType RAMS7200BoolTrans::isA() const { + return (TransformationType) RAMS7200DrvBoolTransType; +} + +TransformationType RAMS7200BoolTrans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + +Transformation *RAMS7200BoolTrans::clone() const { + return new RAMS7200BoolTrans; +} + +int RAMS7200BoolTrans::itemSize() const { + return size; +} + +VariableType RAMS7200BoolTrans::getVariableType() const { + return BIT_VAR; +} + + +PVSSboolean RAMS7200BoolTrans::toPeriph(PVSSchar *buffer, PVSSuint len, const Variable &var, const PVSSuint subix) const { + + if(var.isA() != BIT_VAR){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "REMUSDRVBoolTrans", "toPeriph", // File and function name + "Wrong variable type " + CharString(subix)// Unfortunately we don't know which DP + ); + return PVSS_FALSE; + } + + *reinterpret_cast(buffer) = (reinterpret_cast(var)).getValue(); + + return PVSS_TRUE; +} + +VariablePtr RAMS7200BoolTrans::toVar(const PVSSchar *buffer, const PVSSuint dlen, const PVSSuint subix) const { + if(dlen && buffer != NULL) + return new BitVar(*reinterpret_cast(buffer)); + + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200BoolTrans", "toVar", // File and function name + "Wrong buffer" // Unfortunately we don't know which DP + ); + return NULL; +} + +}//namespace diff --git a/Transformations/RAMS7200BoolTrans.hxx b/Transformations/RAMS7200BoolTrans.hxx new file mode 100644 index 0000000..844ad9e --- /dev/null +++ b/Transformations/RAMS7200BoolTrans.hxx @@ -0,0 +1,80 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200BOOLTRANS_HXX_ +#define RAMS7200BOOLTRANS_HXX_ + +#include + +namespace Transformations{ + +class RAMS7200BoolTrans: public Transformation { + /*! + * Transformations typ + * \return transformation type + */ + TransformationType isA() const; + /*! + * Transformations typ comparison + * \param type object to return type + * \return transformation type + */ + TransformationType isA(TransformationType type) const; + + /*! + * Size of transformation buffer + * \return size of buffer + */ + int itemSize() const; + + /*! + * The type of Variable we are expecting here + * \return actual variable type + */ + VariableType getVariableType() const; + + /*! + * Clone of our class + * \return pointer to new object + */ + Transformation *clone() const; + + /*! + * Conversion from PVSS to Hardware + * \param dataPtr pointer to buffer where data will be written + * \param len size of data buffer + * \param var reference to current translated value + * \param subix subindex of value in data point + * \return flag if translation was successful + */ + PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, + const PVSSuint subix) const; + + /*! + * Conversion from Hardware to PVSS + * \param data pointer to buffer from where data will be read + * \param dlen length of data buffer + * \param subix subindex of value associated with peripheral address + * \return flag if translation was successful + */ + VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, + const PVSSuint subix) const; + +private: + const static uint8_t size = sizeof(bool); +}; + +}//namepsace +#endif /* RAMS7200BOOLTRANS_HXX_ */ + diff --git a/Transformations/RAMS7200FloatTrans.cxx b/Transformations/RAMS7200FloatTrans.cxx new file mode 100644 index 0000000..025bcbc --- /dev/null +++ b/Transformations/RAMS7200FloatTrans.cxx @@ -0,0 +1,86 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200FloatTrans.hxx" + +#include "Transformations/RAMS7200Int16Trans.hxx" + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" +#include "Common/Utils.hxx" + +#include + +#include + +namespace Transformations{ + +TransformationType RAMS7200FloatTrans::isA() const { + return (TransformationType) RAMS7200DrvFloatTransType; +} + +TransformationType RAMS7200FloatTrans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + +Transformation *RAMS7200FloatTrans::clone() const { + return new RAMS7200FloatTrans; +} + +int RAMS7200FloatTrans::itemSize() const { + return size; +} + +VariableType RAMS7200FloatTrans::getVariableType() const { + return FLOAT_VAR; +} + +PVSSboolean RAMS7200FloatTrans::toPeriph(PVSSchar *buffer, PVSSuint len, const Variable &var, const PVSSuint subix) const { + + if(var.isA() != FLOAT_VAR){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200FloatTrans", "toPeriph", // File and function name + "Wrong variable type" // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + reinterpret_cast(buffer)[subix] = Common::Utils::CopyNSwapBytes((reinterpret_cast(var)).getValue()); + return PVSS_TRUE; +} + +VariablePtr RAMS7200FloatTrans::toVar(const PVSSchar *buffer, const PVSSuint dlen, const PVSSuint subix) const { + + if(buffer == NULL || dlen%size > 0 || dlen < size*(subix+1)){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200FloatTrans", "toVar", // File and function name + "Null buffer pointer or wrong length: " + CharString(dlen) // Unfortunately we don't know which DP + ); + return NULL; + } + + return new FloatVar(Common::Utils::CopyNSwapBytes(reinterpret_cast(buffer)[subix])); +} + +}//namespace diff --git a/Transformations/RAMS7200FloatTrans.hxx b/Transformations/RAMS7200FloatTrans.hxx new file mode 100644 index 0000000..425bd8e --- /dev/null +++ b/Transformations/RAMS7200FloatTrans.hxx @@ -0,0 +1,81 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200FLOATTRANS_HXX_ +#define RAMS7200FLOATTRANS_HXX_ + +#include + +namespace Transformations{ + +class RAMS7200FloatTrans: public Transformation { + /*! + * Transformations typ + * \return transformation type + */ + TransformationType isA() const; + /*! + * Transformations typ comparison + * \param type object to return type + * \return transformation type + */ + TransformationType isA(TransformationType type) const; + + /*! + * Size of transformation buffer + * \return size of buffer + */ + int itemSize() const; + + /*! + * The type of Variable we are expecting here + * \return actual variable type + */ + VariableType getVariableType() const; + + /*! + * Clone of our class + * \return pointer to new object + */ + Transformation *clone() const; + + /*! + * Conversion from PVSS to Hardware + * \param dataPtr pointer to buffer where data will be written + * \param len size of data buffer + * \param var reference to current translated value + * \param subix subindex of value in data point + * \return flag if translation was successful + */ + PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, + const PVSSuint subix) const; + + /*! + * Conversion from Hardware to PVSS + * \param data pointer to buffer from where data will be read + * \param dlen length of data buffer + * \param subix subindex of value associated with peripheral address + * \return flag if translation was successful + */ + VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, + const PVSSuint subix) const; + + +private: + const static uint8_t size = sizeof(float); +}; + + +}//namespace +#endif /* RAMS7200FLOATTRANS_HXX_ */ diff --git a/Transformations/RAMS7200Int16Trans.cxx b/Transformations/RAMS7200Int16Trans.cxx new file mode 100644 index 0000000..3a50bb4 --- /dev/null +++ b/Transformations/RAMS7200Int16Trans.cxx @@ -0,0 +1,90 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200Int16Trans.hxx" + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" +#include "Common/Utils.hxx" + +#include + +#include + +namespace Transformations { + +TransformationType RAMS7200Int16Trans::isA() const { + return (TransformationType) RAMS7200DrvInt16TransType; +} + +TransformationType RAMS7200Int16Trans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + +Transformation *RAMS7200Int16Trans::clone() const { + return new RAMS7200Int16Trans; +} + +int RAMS7200Int16Trans::itemSize() const { + return size; +} + +VariableType RAMS7200Int16Trans::getVariableType() const { + return INTEGER_VAR; +} + + +PVSSboolean RAMS7200Int16Trans::toPeriph(PVSSchar *buffer, PVSSuint len, const Variable &var, const PVSSuint subix) const { + + if(var.isA() != INTEGER_VAR){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Int16Trans", "toPeriph", // File and function name + "Wrong variable type" // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + + Common::Logger::globalInfo(Common::Logger::L2,"RAMS7200Int16Trans::toPeriph : Ineteger var received in transformation toPeriph, val is: ", std::to_string(((reinterpret_cast(var)).getValue())).c_str()); + // this one is a bit special as the number is handled by wincc oa as int32, but we handle it as 16 bit integer + // thus any info above the 16 first bits is lost + reinterpret_cast(buffer)[subix] = Common::Utils::CopyNSwapBytes(reinterpret_cast(var).getValue()); + + return PVSS_TRUE; +} + +VariablePtr RAMS7200Int16Trans::toVar(const PVSSchar *buffer, const PVSSuint dlen, const PVSSuint subix) const { + + if(buffer == NULL || dlen%size > 0 || dlen < size*(subix+1)){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Int16Trans", "toVar", // File and function name + "Null buffer pointer or wrong length: " + CharString(dlen) // Unfortunately we don't know which DP + ); + return NULL; + } + // this one is a bit special as the number is handled by wincc oa as int32, but we handle it as 16 bit integer + return new IntegerVar(Common::Utils::CopyNSwapBytes(*reinterpret_cast(buffer + (subix * size)))); +} + +}//namespace diff --git a/Transformations/RAMS7200Int16Trans.hxx b/Transformations/RAMS7200Int16Trans.hxx new file mode 100644 index 0000000..426cbc7 --- /dev/null +++ b/Transformations/RAMS7200Int16Trans.hxx @@ -0,0 +1,80 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200INT16TRANS_HXX_ +#define RAMS7200INT16TRANS_HXX_ + +#include +namespace Transformations { + + +class RAMS7200Int16Trans: public Transformation { + /*! + * Transformations typ + * \return transformation type + */ + TransformationType isA() const; + /*! + * Transformations typ comparison + * \param type object to return type + * \return transformation type + */ + TransformationType isA(TransformationType type) const; + + /*! + * Size of transformation buffer + * \return size of buffer + */ + int itemSize() const; + + /*! + * The type of Variable we are expecting here + * \return actual variable type + */ + VariableType getVariableType() const; + + /*! + * Clone of our class + * \return pointer to new object + */ + Transformation *clone() const; + + /*! + * Conversion from PVSS to Hardware + * \param dataPtr pointer to buffer where data will be written + * \param len size of data buffer + * \param var reference to current translated value + * \param subix subindex of value in data point + * \return flag if translation was successful + */ + PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, + const PVSSuint subix) const; + + /*! + * Conversion from Hardware to PVSS + * \param data pointer to buffer from where data will be read + * \param dlen length of data buffer + * \param subix subindex of value associated with peripheral address + * \return flag if translation was successful + */ + VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, + const PVSSuint subix) const; + +private: + const static uint8_t size = sizeof(int16_t); +}; + +} +#endif /* RAMS7200INT16TRANS_HXX_ */ + diff --git a/Transformations/RAMS7200Int32Trans.cxx b/Transformations/RAMS7200Int32Trans.cxx new file mode 100644 index 0000000..c96e423 --- /dev/null +++ b/Transformations/RAMS7200Int32Trans.cxx @@ -0,0 +1,84 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200Int32Trans.hxx" + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" +#include "Common/Utils.hxx" + +#include + +#include + +namespace Transformations { + +TransformationType RAMS7200Int32Trans::isA() const { + return (TransformationType) RAMS7200DrvInt32TransType; +} + +TransformationType RAMS7200Int32Trans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + +Transformation *RAMS7200Int32Trans::clone() const { + return new RAMS7200Int32Trans; +} + +int RAMS7200Int32Trans::itemSize() const { + return size; +} + +VariableType RAMS7200Int32Trans::getVariableType() const { + return INTEGER_VAR; +} + +PVSSboolean RAMS7200Int32Trans::toPeriph(PVSSchar *buffer, PVSSuint len, const Variable &var, const PVSSuint subix) const { + + if(var.isA() != INTEGER_VAR /* || subix >= Transformation::getNumberOfElements() */){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Int32Trans", "toPeriph", // File and function name + "Wrong variable type or wrong length: " + CharString(len) + ", subix: " + CharString(subix) // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + Common::Logger::globalInfo(Common::Logger::L2,"RAMS7200Int32Trans::toPeriph : Integer32 var received in transformation toPeriph, val is: ", std::to_string(((reinterpret_cast(var)).getValue())).c_str()); + reinterpret_cast(buffer)[subix] = Common::Utils::CopyNSwapBytes(reinterpret_cast(var).getValue()); + return PVSS_TRUE; +} + +VariablePtr RAMS7200Int32Trans::toVar(const PVSSchar *buffer, const PVSSuint dlen, const PVSSuint subix) const { + + if(buffer == NULL || dlen%size > 0 || dlen < size*(subix+1)){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Int32Trans", "toVar", // File and function name + "Null buffer pointer or wrong length: " + CharString(dlen) // Unfortunately we don't know which DP + ); + return NULL; + } + return new IntegerVar( Common::Utils::CopyNSwapBytes(reinterpret_cast(buffer)[subix])); +} + +}//namespace diff --git a/Transformations/RAMS7200Int32Trans.hxx b/Transformations/RAMS7200Int32Trans.hxx new file mode 100644 index 0000000..00e685e --- /dev/null +++ b/Transformations/RAMS7200Int32Trans.hxx @@ -0,0 +1,81 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200INT32TRANS_HXX_ +#define RAMS7200INT32TRANS_HXX_ + +#include +namespace Transformations { + + +class RAMS7200Int32Trans: public Transformation { + /*! + * Transformations typ + * \return transformation type + */ + TransformationType isA() const; + /*! + * Transformations typ comparison + * \param type object to return type + * \return transformation type + */ + TransformationType isA(TransformationType type) const; + + /*! + * Size of transformation buffer + * \return size of buffer + */ + int itemSize() const; + + /*! + * The type of Variable we are expecting here + * \return actual variable type + */ + VariableType getVariableType() const; + + /*! + * Clone of our class + * \return pointer to new object + */ + Transformation *clone() const; + + /*! + * Conversion from PVSS to Hardware + * \param dataPtr pointer to buffer where data will be written + * \param len size of data buffer + * \param var reference to current translated value + * \param subix subindex of value in data point + * \return flag if translation was successful + */ + PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, + const PVSSuint subix) const; + + /*! + * Conversion from Hardware to PVSS + * \param data pointer to buffer from where data will be read + * \param dlen length of data buffer + * \param subix subindex of value associated with peripheral address + * \return flag if translation was successful + */ + VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, + const PVSSuint subix) const; + +private: + const static uint8_t size = sizeof(int32_t); +}; + +} + +#endif /* RAMS7200INT32TRANS_HXX_ */ + diff --git a/Transformations/RAMS7200StringTrans.cxx b/Transformations/RAMS7200StringTrans.cxx new file mode 100644 index 0000000..9e5da6a --- /dev/null +++ b/Transformations/RAMS7200StringTrans.cxx @@ -0,0 +1,112 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +// Our transformation class PVSS <--> Hardware +#include "RAMS7200StringTrans.hxx" +#include // The Error handler Basics/Utilities +#include // The TextVar class + + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" + +//---------------------------------------------------------------------------- +namespace Transformations { + + +//RAMS7200StringTrans::RAMS7200StringTrans() : Transformation() { } + +TransformationType RAMS7200StringTrans::isA() const +{ + return (TransformationType) RAMS7200DrvStringTransType; +} + +TransformationType RAMS7200StringTrans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + + + +//---------------------------------------------------------------------------- + +Transformation *RAMS7200StringTrans::clone() const +{ + return new RAMS7200StringTrans; +} + +//---------------------------------------------------------------------------- +// Our item size. The max we will use is 256 Bytes. +// This is an arbitrary value! A Transformation for a long e.g. would return 4 + +int RAMS7200StringTrans::itemSize() const +{ + return _size; +} + +//---------------------------------------------------------------------------- +// Our preferred Variable type. Data will be converted to this type +// before toPeriph is called. + +VariableType RAMS7200StringTrans::getVariableType() const +{ + return TEXT_VAR; +} + +PVSSboolean RAMS7200StringTrans::toPeriph(PVSSchar *buffer, PVSSuint len, + const Variable &var, const PVSSuint subix) const +{ + + // Be paranoic, check variable type + if ( var.isA() != TEXT_VAR ) + { + // Throw error message + ErrHdl::error( + ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200StringTrans", "toPeriph", // File and function name + "Wrong variable type for data" // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + + const TextVar tv = reinterpret_cast(var); + if(tv.getString().len() >= _size){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200StringTrans", "toPeriph", // File and function name + "String too long" // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + memset(buffer, 0, len); + snprintf( (char *) buffer, len, "%s", tv.getValue()); + return PVSS_TRUE; +} + +VariablePtr RAMS7200StringTrans::toVar(const PVSSchar *buffer, const PVSSuint dlen, + const PVSSuint /* subix */) const +{ + return new TextVar((const char*)buffer, (PVSSuint)strnlen((const char*)buffer, dlen)); +} + + +}//namespace diff --git a/Transformations/RAMS7200StringTrans.hxx b/Transformations/RAMS7200StringTrans.hxx new file mode 100644 index 0000000..ed82a5d --- /dev/null +++ b/Transformations/RAMS7200StringTrans.hxx @@ -0,0 +1,63 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200StringTrans_H +#define RAMS7200StringTrans_H + +#include + +// Our Transformation class for Text +// As the Transformation really depends on the format of data you send and +// receive in your protocol (see HWService), this template is just an +// example. +// Things you have to change are marked with TODO + + +namespace Transformations { + +class RAMS7200StringTrans : public Transformation +{ + public: + // TODO probably your ctor looks completely different ... + //RAMS7200StringTrans(); + virtual ~RAMS7200StringTrans() {} + + virtual TransformationType isA() const; + + virtual TransformationType isA(TransformationType type) const; + + // (max) size of one item. This is needed by DrvManager to + // create the buffer used in toPeriph and by the Low-Level-Compare + // For our Text-Transformation we set it arbitrarly to 256 Bytes + virtual int itemSize() const; + + // The type of Variable we are expecting here + virtual VariableType getVariableType() const; + + // Clone of our class + virtual Transformation *clone() const; + + // Conversion from PVSS to Hardware + virtual PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, const PVSSuint subix) const; + + // Conversion from Hardware to PVSS + virtual VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, const PVSSuint subix) const; +private: + const static size_t _size = 255; + +}; + +} + +#endif diff --git a/Transformations/RAMS7200Uint8Trans.cxx b/Transformations/RAMS7200Uint8Trans.cxx new file mode 100644 index 0000000..4f7b1a1 --- /dev/null +++ b/Transformations/RAMS7200Uint8Trans.cxx @@ -0,0 +1,85 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#include + +#include "RAMS7200Uint8Trans.hxx" + +#include "RAMS7200HWMapper.hxx" + +#include "Common/Logger.hxx" + +#include + +#include + +namespace Transformations{ + +TransformationType RAMS7200Uint8Trans::isA() const { + return (TransformationType) RAMS7200DrvUint8TransType; +} + +TransformationType RAMS7200Uint8Trans::isA(TransformationType type) const { + if (type == isA()) + return type; + else + return Transformation::isA(type); +} + +Transformation *RAMS7200Uint8Trans::clone() const { + return new RAMS7200Uint8Trans; +} + +int RAMS7200Uint8Trans::itemSize() const { + return size; +} + +VariableType RAMS7200Uint8Trans::getVariableType() const { + return INTEGER_VAR; +} + +PVSSboolean RAMS7200Uint8Trans::toPeriph(PVSSchar *buffer, PVSSuint len, const Variable &var, const PVSSuint subix) const { + + if(var.isA() != INTEGER_VAR){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Uint8Trans", "toPeriph", // File and function name + "Wrong variable type" // Unfortunately we don't know which DP + ); + + return PVSS_FALSE; + } + // this one is a bit special as the number is handled by wincc oa as int32, but we handle it as 8 bit unsigned integer + // thus any info above the 8 first bits is lost + *(reinterpret_cast(buffer + (subix * size))) = (uint8_t)(reinterpret_cast(var)).getValue(); + return PVSS_TRUE; +} + +VariablePtr RAMS7200Uint8Trans::toVar(const PVSSchar *buffer, const PVSSuint dlen, const PVSSuint subix) const { + + if(buffer == NULL || dlen%size > 0 || dlen < size*(subix+1)){ + ErrHdl::error(ErrClass::PRIO_SEVERE, // Data will be lost + ErrClass::ERR_PARAM, // Wrong parametrization + ErrClass::UNEXPECTEDSTATE, // Nothing else appropriate + "RAMS7200Uint8Trans", "toVar", // File and function name + "Null buffer pointer or wrong length: " + CharString(dlen) // Unfortunately we don't know which DP + ); + return NULL; + } + // this one is a bit special as the number is handled by wincc oa as int32, but we handle it as 8 bit unsigned integer + return new IntegerVar((int32_t)*reinterpret_cast(buffer + (subix * size))); +} + +}//namespace diff --git a/Transformations/RAMS7200Uint8Trans.hxx b/Transformations/RAMS7200Uint8Trans.hxx new file mode 100644 index 0000000..4af8371 --- /dev/null +++ b/Transformations/RAMS7200Uint8Trans.hxx @@ -0,0 +1,81 @@ +/** © Copyright 2022 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Adrien Ledeul (HSE) + * + **/ + +#ifndef RAMS7200UINT8TRANS_HXX_ +#define RAMS7200UINT8TRANS_HXX_ + +#include + +namespace Transformations{ + +class RAMS7200Uint8Trans: public Transformation { + /*! + * Transformations type + * \return transformation type + */ + TransformationType isA() const; + /*! + * Transformations typ comparison + * \param type object to return type + * \return transformation type + */ + TransformationType isA(TransformationType type) const; + + /*! + * Size of transformation buffer + * \return size of buffer + */ + int itemSize() const; + + /*! + * The type of Variable we are expecting here + * \return actual variable type + */ + VariableType getVariableType() const; + + /*! + * Clone of our class + * \return pointer to new object + */ + Transformation *clone() const; + + /*! + * Conversion from PVSS to Hardware + * \param dataPtr pointer to buffer where data will be written + * \param len size of data buffer + * \param var reference to current translated value + * \param subix subindex of value in data point + * \return flag if translation was successful + */ + PVSSboolean toPeriph(PVSSchar *dataPtr, PVSSuint len, const Variable &var, + const PVSSuint subix) const; + + /*! + * Conversion from Hardware to PVSS + * \param data pointer to buffer from where data will be read + * \param dlen length of data buffer + * \param subix subindex of value associated with peripheral address + * \return flag if translation was successful + */ + VariablePtr toVar(const PVSSchar *data, const PVSSuint dlen, + const PVSSuint subix) const; + + +private: + const static uint8_t size = sizeof(uint8_t); +}; + +}//namesace + +#endif /* RAMS7200UINT8TRANS_HXX_ */ diff --git a/config.h.in b/config.h.in new file mode 100644 index 0000000..2f6c012 --- /dev/null +++ b/config.h.in @@ -0,0 +1,21 @@ +/** © Copyright 2024 CERN + * + * This software is distributed under the terms of the + * GNU Lesser General Public Licence version 3 (LGPL Version 3), + * copied verbatim in the file “LICENSE” + * + * In applying this licence, CERN does not waive the privileges + * and immunities granted to it by virtue of its status as an + * Intergovernmental Organization or submit itself to any jurisdiction. + * + * Author: Alexandru Savulescu (HSE) + * + **/ + +#pragma once + +#define PROJECT_NAME "@PROJECT_NAME@" +#define PROJECT_VER "@PROJECT_VERSION@" +#define PROJECT_VER_MAJOR "@PROJECT_VERSION_MAJOR@" +#define PROJECT_VER_MINOR "@PROJECT_VERSION_MINOR@" +#define PTOJECT_VER_PATCH "@PROJECT_VERSION_PATCH@" diff --git a/doc/RAMS7200Design.svg b/doc/RAMS7200Design.svg new file mode 100644 index 0000000..57f83eb --- /dev/null +++ b/doc/RAMS7200Design.svg @@ -0,0 +1 @@ +Reads the configuration entries,remote and local TSAP port,pollingInterval, smoothing, cycle interval and max numberof IO failures for reconnection viaRAMS7200Resources::readSection()Readconfig.RAMS7200fileRAMS7200HWService::start()RAMS7200HWService::handleNewMS()(also callback for new MS addressed in the driverviasetNewMSCallback())Launch a thread for each IP Address associated with the driver ThreadPerIP for IP Address 1ThreadPerIP for IP Address ...ThreadPerIP for IP Address NRAMS7200LibFacadeRAMS7200HWService::writeData()Decode HWObject from WinCCobject is an MS itemRAMS7200MS::queuePLCItem()object is Config itemApply configRAMS7200HWService::workProc()DrvManager::getSelfPtr()->toDppush DPE entry to WinCCyesitem addressed in the driver?yes_toDPqueueitems to process?noThreadPerIPRAMS7200LibFacade.WriteToPLC()(sends the queued items to the PLC)RAMS7200LibFacade.Poll()smoothing enabled?yesnocompare last values and send only if differentsend all polled valuesRAMS7200HWService::queueToDP()callbackyespolled values to process?noyes_driverRun & ms._run?noRAMS7200LibFacade.poll()Loop Over all Addresses of the MSAdd to poll listYesCurrent Time - Last Write time of Address >= Polling Timeread from PLC via snap7YesPoll List is not empty \ No newline at end of file diff --git a/doc/RAMS7200Design.uml b/doc/RAMS7200Design.uml new file mode 100644 index 0000000..e779f4b --- /dev/null +++ b/doc/RAMS7200Design.uml @@ -0,0 +1,106 @@ +@startuml +start + +:Read config.RAMS7200 file; +note right + Reads the configuration entries,remote and local TSAP port, + pollingInterval, smoothing, cycle interval and max number + of IO failures for reconnection via + RAMS7200Resources::readSection() +end note +:RAMS7200HWService::start() ; + +:Launch a thread for each IP Address associated with the driver +; +note left + RAMS7200HWService::handleNewMS() + (also callback for new MS addressed in the driver + via setNewMSCallback()) +end note +fork + :ThreadPerIP for IP Address 1; + (F) + detach +fork again + :ThreadPerIP for IP Address ...; + (F) + detach +fork again + -[#black,dotted]-> + :ThreadPerIP for IP Address N; + -[#black,dotted]-> + (F) + note right + RAMS7200LibFacade + end note + detach +end fork + + +fork + partition RAMS7200HWService::writeData() { + start + :Decode HWObject from WinCC; + if(object is an MS item) then + :RAMS7200MS::queuePLCItem(); + else if(object is Config item) then + :Apply config; + endif + stop + } + partition RAMS7200HWService::workProc() { + start + while (_toDPqueue items to process?) is (yes) + if (item addressed in the driver?) then (yes) + :push DPE entry to WinCC; + note right + DrvManager::getSelfPtr()->toDp + end note + endif + endwhile (no) + stop + } + +fork again + partition ThreadPerIP { + start + while(_driverRun & ms._run?) is (yes) + (F) + note right + RAMS7200LibFacade.WriteToPLC() + (sends the queued items to the PLC) + end note + (F) + note right + RAMS7200LibFacade.Poll() + end note + while (polled values to process?) is (yes) + if (smoothing enabled?) then (yes) + :compare last values and send only if different; + else(no) + :send all polled values; + endif + + :RAMS7200HWService::queueToDP() callback; + endwhile (no) + endwhile (no) + stop + } +partition RAMS7200LibFacade.poll() { + start + partition Loop Over all Addresses of the MS { + if(Current Time - Last Write time of Address >= Polling Time) then (Yes) + :Add to poll list; + endif + } + if(Poll List is not empty) then (Yes) + :read from PLC via snap7; + endif + stop +} + +end fork + + +end +@enduml \ No newline at end of file diff --git a/external/libsnap7 b/external/libsnap7 new file mode 160000 index 0000000..92aeea9 --- /dev/null +++ b/external/libsnap7 @@ -0,0 +1 @@ +Subproject commit 92aeea97b08772b90028e3e280b35416c5f0bf20 diff --git a/test.cpp b/test.cpp new file mode 100644 index 0000000..d2d403b --- /dev/null +++ b/test.cpp @@ -0,0 +1,359 @@ +/*=============================================================================| +| PROJECT SNAP7 1.4.0 | +|==============================================================================| +| Copyright (C) 2013, 2014 Davide Nardella | +| All rights reserved. | +|==============================================================================| +| SNAP7 is free software: you can redistribute it and/or modify | +| it under the terms of the Lesser GNU General Public License as published by | +| the Free Software Foundation, either version 3 of the License, or | +| (at your option) any later version. | +| | +| It means that you can distribute your commercial software linked with | +| SNAP7 without the requirement to distribute the source code of your | +| application and without the requirement that your application be itself | +| distributed under LGPL. | +| | +| SNAP7 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 | +| Lesser GNU General Public License for more details. | +| | +| You should have received a copy of the GNU General Public License and a | +| copy of Lesser GNU General Public License along with Snap7. | +| If not, see http://www.gnu.org/licenses/ | +|==============================================================================| +| | +| Client Example | +| | +|=============================================================================*/ + +#include +#include +#include +#include +#include "snap7.h" +#include "Common/S7Utils.hxx" + + +#ifdef OS_WINDOWS +# define WIN32_LEAN_AND_MEAN +# include +#endif + + TS7Client *Client; + + byte Buffer[65536]; // 64 K buffer + int SampleDBNum = 1000; + + char *Address; // PLC IP Address + int Rack=0,Slot=2; // Default Rack and Slot + + int ok = 0; // Number of test pass + int ko = 0; // Number of test failure + + bool JobDone=false; + int JobResult=0; + +//------------------------------------------------------------------------------ +// Async completion callback +//------------------------------------------------------------------------------ +// This is a simply text demo, we use callback only to set an internal flag... +void S7API CliCompletion(void *usrPtr, int opCode, int opResult) +{ + JobResult=opResult; + JobDone = true; +} + +//------------------------------------------------------------------------------ +// Usage Syntax +//------------------------------------------------------------------------------ +void Usage() +{ + printf("Usage\n"); + printf(" client [Rack=0 Slot=2]\n"); + printf("Example\n"); + printf(" client 192.168.1.101 0 2\n"); + printf("or\n"); + printf(" client 192.168.1.101\n"); + getchar(); +} + +//------------------------------------------------------------------------------ +// Check error +//------------------------------------------------------------------------------ +bool Check(int Result, const char * function) +{ + printf("\n"); + printf("+-----------------------------------------------------\n"); + printf("| %s\n",function); + printf("+-----------------------------------------------------\n"); + if (Result==0) { + printf("| Result : OK\n"); + printf("| Execution time : %d ms\n",Client->ExecTime()); + printf("+-----------------------------------------------------\n"); + ok++; + } + else { + printf("| ERROR !!! \n"); + if (Result<0) + printf("| Library Error (-1)\n"); + else + printf("| %s\n",CliErrorText(Result).c_str()); + printf("+-----------------------------------------------------\n"); + ko++; + } + return Result==0; +} + +TS7DataItem RAMS7200Read(std::string RAMS7200Address, void* val) +{ + TS7DataItem item = Common::S7Utils::TS7DataItemFromAddress(RAMS7200Address, true); + int memSize = ( Common::S7Utils::DataSizeByte(item.WordLen )*item.Amount); + + printf("-------------read RAMS7200Address=>(Area, Start, WordLen, Amount): memSize : %s =>(%d, %d, %d, %d) : %dB", RAMS7200Address.c_str(), item.Area, item.Start, item.WordLen, item.Amount, memSize); + + if(Client->ReadMultiVars(&item, 1) == 0){ + if(item.WordLen == S7WLWord){ + uint16_t wordVal = Common::Utils::CopyNSwapBytes(item.pdata); + std::memcpy(val, &wordVal, memSize); + } + else{ + std::memcpy(val, item.pdata, memSize); + } + printf(Common::S7Utils::DisplayTS7DataItem(&item, Common::S7Utils::Operation::READ).c_str()); + } + else{ + printf("--> read NOK!\n"); + } + return item; +} + +TS7DataItem RAMS7200Write(std::string RAMS7200Address, void* val) +{ + TS7DataItem item = Common::S7Utils::TS7DataItemFromAddress(RAMS7200Address, true); + int memSize = ( Common::S7Utils::DataSizeByte(item.WordLen )*item.Amount); + if(item.WordLen == S7WLWord){ + uint16_t wordVal = Common::Utils::CopyNSwapBytes(val); + std::memcpy(item.pdata , &wordVal , memSize); + } + else{ + std::memcpy(item.pdata , val , memSize); + } + printf("-------------write RAMS7200Address=>(Area, Start, WordLen, Amount): memSize : %s =>(%d, %d, %d, %d) : %dB", RAMS7200Address.c_str(), item.Area, item.Start, item.WordLen, item.Amount, memSize); + if(Client->WriteMultiVars(&item, 1) == 0){ + printf("--> write OK!\n"); + } + else{ + printf("--> write NOK!\n"); + } + return item; +} + + + + +//------------------------------------------------------------------------------ +// Unit Connection +//------------------------------------------------------------------------------ +bool CliConnect() +{ + Client->SetConnectionParams(Address, 0x1101, 0x1100); + printf("Trying to connect to %s", Address); + int res = Client->Connect(); + if (Check(res,"UNIT Connection")) { + printf(" Connected to : %s (Rack=%d, Slot=%d)\n",Address,Rack,Slot); + printf(" PDU Requested : %d bytes\n",Client->PDURequested()); + printf(" PDU Negotiated : %d bytes\n",Client->PDULength()); + }; + return res==0; +} +//------------------------------------------------------------------------------ +// Unit Disconnection +//------------------------------------------------------------------------------ +void CliDisconnect() +{ + Client->Disconnect(); +} +//------------------------------------------------------------------------------ +// Perform readonly tests, no cpu status modification +//------------------------------------------------------------------------------ +void PerformTests() +{ + std::string addresses[] = { + "VW1984", //VW1984=13220 + "VB2978.20", //VB2978.20='29 1-035', + "VW2000", + "VW2002" + "VB1604", //VB1604=8 + "V1604.2", //V1604.2=0 + "V1604.3", //V1604.3=1 + "V2640.0", + "V2640.02", + "V2640.04", + "V2640.06", + "V2641.0", + "V2641.02", + "V2641.04", + "V2641.06", + //"M10.0", //M10.0=1 + //"M10.1", //M10.1=0 Read-only? + //"E0.0", //E0.0=1 Read-only? + //"E1.1", //E0.0=0 Read-only? + //"A0.2", //A0.2=1 Read-only? + //"A0.3", //A0.3=0 Read-only? + //"I0.2", //I0.2=1 Read-only? + //"I0.3", //I0.3=0 Read-only? + //"Q0.2", //Q0.2=1 Read-only? + //"Q0.3" //Q0.3=0 Read-only? + + }; + + for(std::string address : addresses){ + TS7DataItem item = Common::S7Utils::TS7DataItemFromAddress(address, true); + switch (item.WordLen){ + case S7WLByte: + if(item.Amount >1){ + printf("Item.amount is : %d\n", item.Amount); + char valInitR[256], valInitW[256], valChangedW[256], valChangedR[256]; + RAMS7200Read(address, &valInitR); + std::memcpy(valChangedW , &valInitR , 256); + valChangedW[0] = valChangedW[0]+1; + RAMS7200Write(address, &valChangedW); + RAMS7200Read(address, &valChangedR); + Check(strcmp(valChangedW,valChangedR), ("IO :" + address).c_str()); + std::memcpy(valInitW , &valInitR , 256); + RAMS7200Write(address, &valInitW); + RAMS7200Read(address, &valInitR); + Check(strcmp(valInitW,valInitR), ("IO re-init :" + address).c_str()); + printf("valInitR: %s\n",valInitR); + printf("valInitW: %s\n",valInitW); + printf("valChangedW: %s\n",valChangedW); + printf("valChangedR: %s\n",valChangedR); + } + else{ + uint8_t valInitR, valInitW, valChangedW, valChangedR; + RAMS7200Read(address, &valInitR); + valChangedW = valInitR == 1 ? 0 : 1; + RAMS7200Write(address, &valChangedW); + RAMS7200Read(address, &valChangedR); + Check((valChangedW==valChangedR) ? 0 : -1, ("IO :" + address).c_str()); + valInitW = valInitR; + RAMS7200Write(address, &valInitW); + RAMS7200Read(address, &valInitR); + Check((valInitW==valInitR) ? 0 : -1, ("IO re-init :" + address).c_str()); + printf("valInitR: %d\n",valInitR); + printf("valInitW: %d\n",valInitW); + printf("valChangedW: %d\n",valChangedW); + printf("valChangedR: %d\n",valChangedR); + } + break; + case S7WLBit:{ + uint8_t valInitR, valInitW, valChangedW, valChangedR; + RAMS7200Read(address, &valInitR); + valChangedW = valInitR == 0x0001 ? 0x0000 : 0x0001; + RAMS7200Write(address, &valChangedW); + RAMS7200Read(address, &valChangedR); + Check((valChangedW==valChangedR) ? 0 : -1, ("IO :" + address).c_str()); + valInitW = valInitR; + RAMS7200Write(address, &valInitW); + RAMS7200Read(address, &valInitR); + Check((valInitW==valInitR) ? 0 : -1, ("IO re-init :" + address).c_str()); + printf("valInitR: %d\n",valInitR); + //hexdump(&valInitR , sizeof(valInitR)); + printf("valInitW: %d\n",valInitW); + //hexdump(&valInitW , sizeof(valInitW)); + printf("valChangedW: %d\n",valChangedW); + //hexdump(&valChangedW , sizeof(valChangedW)); + printf("valChangedR: %d\n",valChangedR); + //hexdump(&valChangedR , sizeof(valChangedR)); + } + break; + case S7WLWord:{ + uint16_t valInitR, valInitW, valChangedW, valChangedR; + RAMS7200Read(address, &valInitR); + valChangedW = valInitR == 1 ? 0 : 1; + RAMS7200Write(address, &valChangedW); + RAMS7200Read(address, &valChangedR); + Check((valChangedW==valChangedR) ? 0 : -1, ("IO :" + address).c_str()); + valInitW = valInitR; + RAMS7200Write(address, &valInitW); + RAMS7200Read(address, &valInitR); + Check((valInitW==valInitR) ? 0 : -1, ("IO re-init :" + address).c_str()); + printf("valInitR: %d\n",valInitR); + printf("valInitW: %d\n",valInitW); + printf("valChangedW: %d\n",valChangedW); + printf("valChangedR: %d\n",valChangedR); + } + break; + case S7WLReal:{ + float valInitR, valInitW, valChangedW, valChangedR; + RAMS7200Read(address, &valInitR); + valChangedW = valInitR == 1.0 ? 0.0 : 1.0; + RAMS7200Write(address, &valChangedW); + RAMS7200Read(address, &valChangedR); + Check((valChangedW==valChangedR) ? 0 : -1, ("IO :" + address).c_str()); + valInitW = valInitR == 1 ? 0 : 1; + RAMS7200Write(address, &valInitW); + RAMS7200Read(address, &valInitR); + Check((valInitW==valInitR) ? 0 : -1, ("IO re-init :" + address).c_str()); + printf("valInitR: %.3f\n",valInitR); + printf("valInitW: %.3f\\n",valInitW); + printf("valChangedW: %.3f\\n",valChangedW); + printf("valChangedR: %.3f\\n",valChangedR); + } + break; + default: + break; + } + } +} + +//------------------------------------------------------------------------------ +// Tests Summary +//------------------------------------------------------------------------------ +void Summary() +{ + printf("\n"); + printf("+-----------------------------------------------------\n"); + printf("| Test Summary \n"); + printf("+-----------------------------------------------------\n"); + printf("| Performed : %d\n",(ok+ko)); + printf("| Passed : %d\n",ok); + printf("| Failed : %d\n",ko); +} +//------------------------------------------------------------------------------ +// Main +//------------------------------------------------------------------------------ +int main(int argc, char* argv[]) +{ +// Get Progran args (we need the client address and optionally Rack and Slot) + if (argc!=2 && argc!=4) + { + Usage(); + return 1; + } + Address=argv[1]; + if (argc==4) + { + Rack=atoi(argv[2]); + Slot=atoi(argv[3]); + } + +// Client Creation + Client= new TS7Client(); + Client->SetAsCallback(CliCompletion,NULL); + +// Connection + if (CliConnect()) + { + PerformTests(); + CliDisconnect(); + }; + +// Deletion + delete Client; + Summary(); + + return 0; +} diff --git a/winccoa/dplist/rams7200_driver_config.dpl b/winccoa/dplist/rams7200_driver_config.dpl new file mode 100644 index 0000000..934f6b2 --- /dev/null +++ b/winccoa/dplist/rams7200_driver_config.dpl @@ -0,0 +1,38 @@ +# ascii dump of database + +# DpType +TypeName +CONFIG_RAMS7200.CONFIG_RAMS7200 1#1 + DebugLvl 21#8 + DriverName 25#9 + IN 1#10 + DrvVersion 25#11 + +# Datapoint/DpId +DpName TypeName ID +CONFIG_RAMS7200_32 CONFIG_RAMS7200 7985959 + + +# Aliases/Comments +AliasId AliasName CommentName +CONFIG_RAMS7200_32.DebugLvl "" lt:1 LANG:10001 "Debug Level@@" +CONFIG_RAMS7200_32.DriverName "" lt:1 LANG:10001 "Driver name@@" +CONFIG_RAMS7200_32.IN.DrvVersion "" lt:1 LANG:10001 "Version@@" + +# DpValue +Manager/User ElementName TypeName _original.._value _original.._status64 _original.._stime +CTL (25)/0 CONFIG_RAMS7200_32.DebugLvl CONFIG_RAMS7200 0 0x8300000000000101 04.06.2024 09:51:32.496 +CTL (25)/0 CONFIG_RAMS7200_32.DriverName CONFIG_RAMS7200 "RAMS7200" 0x8300000000000101 04.06.2024 09:51:32.496 +CTL (25)/0 CONFIG_RAMS7200_32.IN.DrvVersion CONFIG_RAMS7200 "2.4.1" 0x8300000000200101 04.06.2024 09:51:32.496 + + +# DistributionInfo +ElementName TypeName _distrib.._type _distrib.._driver +CONFIG_RAMS7200_32.DebugLvl CONFIG_RAMS7200 56 \32 +CONFIG_RAMS7200_32.IN.DrvVersion CONFIG_RAMS7200 56 \32 + + +# PeriphAddrMain +ElementName TypeName _address.._type _address.._reference _address.._poll_group _address.._connection _address.._offset _address.._subindex _address.._direction _address.._internal _address.._lowlevel _address.._active _address.._start _address.._interval _address.._reply _address.._datatype _address.._drv_ident +CONFIG_RAMS7200_32.DebugLvl CONFIG_RAMS7200 16 "_DEBUGLVL" 0 0 \1 0 0 1 01.01.1970 00:00:00.000 01.01.1970 00:00:00.000 01.01.1970 00:00:00.000 1002 "RAMS7200" +CONFIG_RAMS7200_32.IN.DrvVersion CONFIG_RAMS7200 16 "_VERSION" 0 0 \2 0 0 1 01.01.1970 00:00:00.000 01.01.1970 00:00:00.000 01.01.1970 00:00:00.000 1005 "RAMS7200" \ No newline at end of file diff --git a/winccoa/panels/para/address_rams7200.pnl b/winccoa/panels/para/address_rams7200.pnl new file mode 100644 index 0000000..b1208a4 --- /dev/null +++ b/winccoa/panels/para/address_rams7200.pnl @@ -0,0 +1,774 @@ + + + + + + + 620 480 + _3DFace + 6 4.5 + True + False + + 96.03287671232877 + None + + + + + + + + 0 + + 29.5 6.5 + True + True + schwarz + _Transparent + 3 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [outline] + 31.5 6.5 + + arial,-1,18,5,50,0,0,0,0,0 + + + Periphery - S7200 + + 0 + 2 + False + True + True + [0s,,,AlignLeft] + + + + + + + + para/dpe.ref + 308 10 + 1 0 0 1 -0.5 -5.5 + 0 + + + $DPE + $1 + + + AlignCenter + + + + + para/lock_unlock.ref + 6 12 + 1 0 0 1 -0.5 -5.5 + 1 + + + $1 + $1 + + + AlignCenter + + + + + 4 + + 10 60 + True + True + _3DText + _Transparent + 4 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [outline] + 1 0 0 1 -0.5 -5.5 + Normal + 10 60 + 601 51 + 0 + True + + + + + 5 + + 29.5 44.5 + True + True + _3DText + _3DFace + 5 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 29.5 44.5 + + arial,-1,13,5,50,0,0,0,0,0 + + + reference: IP$Var$pollingTime + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 6 + + 509.5 44.5 + True + True + _3DText + _3DFace + 6 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 509.5 44.5 + + arial,-1,13,5,50,0,0,0,0,0 + + + driver number + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 7 + + 10 200 + True + True + _3DText + _Transparent + 7 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [outline] + 0.2675 0 0 0.655 6.824999999999999 -7.25 + Normal + 10 200 + 601 101 + 0 + True + + + + + 8 + + 294.5 113.75 + True + True + _3DText + _3DFace + 8 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 29.5 113.75 + + arial,-1,13,5,50,0,0,0,0,0 + + + direction + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 9 + + 10 130 + True + True + _3DText + _Transparent + 9 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [outline] + 0.4172222222222222 0 0 1 205.4944444444444 -5.5 + Normal + 10 130 + 601 51 + 0 + True + + + + + 10 + + 229.5 114.5 + True + True + _3DText + _3DFace + 10 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 229.5 114.5 + + arial,-1,13,5,50,0,0,0,0,0 + + + Transformation + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 11 + + 161.4375 328.75 + True + False + _WindowText + _3DFace + 11 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 163.4375 330.75 + + Arial,-1,13,5,40,0,0,0,0,0 + + + Subindex + + 0 + 2 + False + True + True + [0s,,,AlignLeft] + + + + + 12 + + 164.5 381.3125 + True + False + _3DText + _3DFace + 12 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 164.5 381.3125 + + arial,-1,13,5,50,0,0,0,0,0 + + + poll group + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 13 + + 269.9999999999999 330.75 + True + False + _3DText + _3DFace + 13 + + + + AlignCenter + Point + _Transparent + False + [solid,oneColor,JoinMiter,CapButt,1] + False + [solid] + 26.99999999999994 330.75 + + arial,-1,13,5,50,0,0,0,0,0 + + + input mode + + 0 + 0 + False + True + True + [0s,,,AlignLeft] + + + + + + + + 14 + + 336 391.125 + True + False + _3DText + _3DFace + 14 + + + + AlignCenter + Point + + arial,-1,13,5,50,0,0,0,0,0 + + 337.5 392.625 + 151 30 + + + + low level comparison + + False + + + + + + + para/buttons.ref + 220 440 + 1 0 0 1 -210 5 + 2 + AlignCenter + + + + + 20 + + 165 395.125 + True + False + _WindowText + _Window + 15 + + + + AlignCenter + Point + + Arial,-1,13,5,40,0,0,0,0,0 + + 165.5 395.625 + 141 24 + Normal + True + [0s,,,AlignLeft] + False + + + + + 23 + + 29.5 347.25 + True + False + _3DText + _3DFace + 16 + + + + AlignCenter + Point + + arial,-1,13,5,50,0,0,0,0,0 + + 30 348.75 + 121 71 + + + + Spontaneous + + False + + + + Polling + + True + + + + Single query + + False + + + + + + + 24 + + 526.5 63.5 + True + True + _WindowText + _Window + 17 + + + + AlignCenter + Point + + arial,-1,13,5,50,0,0,0,0,0 + + 529 65 + 57 24 + 1 + 256 + 1 + 1 + + + + + 25 + + 29.5 133.2857142857143 + True + True + _3DText + _3DFace + 18 + + + + AlignCenter + Point + + arial,-1,13,5,50,0,0,0,0,0 + + 30 134.25 + 121 46 + + + + Out + + False + + + + In + + True + + + + In/Out + + False + + + + + + + 26 + + 224.3333333333333 134.5 + True + True + {0,0,0} + _Window + 19 + + + + AlignCenter + Point + + arial,-1,13,5,50,0,0,0,0,0 + + 226.8333333333333 137 + 217 26 + + + + Bool + + True + + + + Char + + False + + + + Int16 + + False + + + + Int32 + + False + + + + Float + + False + + + + String + + False + + + True + + + + + 27 + + 494.5 126.25 + True + True + _3DText + _3DFace + 20 + + + + AlignCenter + Point + + Arial,-1,13,5,40,0,0,0,0,0 + + 495 126.75 + 91 31 + + + + Active + + False + + + + + + + 28 + + 164.5 348.875 + True + False + _WindowText + _Window + 21 + + + + AlignCenter + Point + + Arial,-1,13,5,40,0,0,0,0,0 + + 165 349.375 + 151 24 + 0 + 100 + 1 + 0 + + + + + 29 + + 28.28571428571429 64.5 + True + True + _WindowText + _Window + 22 + + + + AlignCenter + Point + + Arial,-1,13,5,40,0,0,0,0,0 + + 30 65 + 481 24 + Normal + True + [0s,,,AlignLeft] + False + + + + diff --git a/winccoa/scripts/libs/rams7200_dpe_addressing.ctl b/winccoa/scripts/libs/rams7200_dpe_addressing.ctl new file mode 100644 index 0000000..f661cd1 --- /dev/null +++ b/winccoa/scripts/libs/rams7200_dpe_addressing.ctl @@ -0,0 +1,134 @@ +/** + * Library of functions used to address RAMS7200 Driver DPE + * @file rams7200_dpe_addressing.ctl + * @author Alexandru Savulescu + * @date 10/06/2024 + * @modifications: + * -[author] [date] [object] +*/ + + + +const unsigned RAMS7200_MODE_OUT = 1; +const unsigned RAMS7200_MODE_IN = 2; +const unsigned RAMS7200_MODE_INOUT = 6; + +const unsigned RAMS7200_DATA_TYPE_BOOL = 1000; +const unsigned RAMS7200_DATA_TYPE_CHAR = 1001; +const unsigned RAMS7200_DATA_TYPE_INT16 = 1002; +const unsigned RAMS7200_DATA_TYPE_INT32 = 1003; +const unsigned RAMS7200_DATA_TYPE_FLOAT = 1004; +const unsigned RAMS7200_DATA_TYPE_STRING = 1005; + +private const unsigned RAMS7200_TYPE = 1; +private const unsigned RAMS7200_DRIVER_NUMBER = 32; +private const unsigned RAMS7200_REFERENCE = 3; +private const unsigned RAMS7200_DIRECTION = 4; +private const unsigned RAMS7200_DATATYPE = 5; +private const unsigned RAMS7200_ACTIVE = 6; +private const unsigned RAMS7200_SUBINDEX = 7; + + +/** + * Called when a DPE connected to this driver is adressed (used to set the proper periph. address config) + * @param dpe path to dpe to address + * @param dataType Data Type (RAMS7200_DATA_TYPE_*) + * @param mode adressing mode ( RAMS7200_MODE_IN or RAMS7200_MODE_OUT or RAMS7200_MODE_INOUT) + * @param driverNum driver manager number + * @param plc_ip S7200 PLC IP + * @param address S7 address + * @param polling_interval + * @return 1 if OK, 0 if not +*/ + +public int RAMS7200_addressDPE(string dpe, unsigned dataType, unsigned mode, unsigned driverNum, string plc_ip, string address, unsigned polling_interval) +{ + dyn_anytype params; + try + { + params[RAMS7200_DRIVER_NUMBER] = driverNum; + params[RAMS7200_DIRECTION]= mode; + params[RAMS7200_ACTIVE] = true; + params[RAMS7200_SUBINDEX] = 0; + params[RAMS7200_DATATYPE] = dataType; + params[RAMS7200_REFERENCE] = plc_ip + "$" + address + "$" + polling_interval; + RAMS7200_setPeriphAddress(dpe, params); + } + catch + { + DebugN("Error: Uncaught exception in RAMS7200_addressDPE: " + getLastException()); + return 0; + } + return 1; +} + + +/** + * Called when a DPE connected to this driver is adressed (used to set the proper periph. address config) + * @param dpe path to dpe to address + * @param dataType Data Type (RAMS7200_DATA_TYPE_*) + * @param mode adressing mode ( RAMS7200_MODE_IN or RAMS7200_MODE_OUT or RAMS7200_MODE_INOUT) + * @param driverNum driver manager number + * @param plc_ip S7200 PLC IP + * @param configName name of the config (e.g. _DEBUGLVL) + * @return 1 if OK, 0 if not +*/ + +public int RAMS7200_addressConfigDPE(string dpe, unsigned dataType, unsigned mode, unsigned driverNum, string configName) +{ + dyn_anytype params; + try + { + params[kafkaAddress_DRIVER_NUMBER] = driverNum; + params[kafkaAddress_DIRECTION]= mode; + params[kafkaAddress_ACTIVE] = true; + params[kafkaAddress_SUBINDEX] = 0; + params[kafkaAddress_DATATYPE] = dataType; + params[kafkaAddress_REFERENCE] = configName; + kafkaAddress_setPeriphAddress(dpe, params); + } + catch + { + DebugN("Error: Uncaught exception in kafkaAddress_addressConfigDPE: " + getLastException()); + return 0; + } + return 1; +} + + + +/** + * Method setting addressing for RAMS7200 datapoints elements + * @param datapoint element for which address will be set + * @param configuration parameteres + */ +private void RAMS7200_setPeriphAddress(string dpe, dyn_anytype configParameters){ + + int i = 1; + dyn_string names; + dyn_anytype values; + + dpSetWait(dpe + ":_distrib.._type", DPCONFIG_DISTRIBUTION_INFO, + dpe + ":_distrib.._driver", configParameters[RAMS7200_DRIVER_NUMBER] ); + dyn_string errors = getLastError(); + if(dynlen(errors) > 0){ + throwError(errors); + DebugN("Error: Could not create the distrib config"); + return; + } + + names[i] = dpe + ":_address.._type"; + values[i++] = DPCONFIG_PERIPH_ADDR_MAIN; + names[i] = dpe + ":_address.._drv_ident"; + values[i++] = "RAMS7200"; + names[i] = dpe + ":_address.._reference"; + values[i++] = configParameters[RAMS7200_REFERENCE]; + names[i] = dpe + ":_address.._mode"; + values[i++] = configParameters[RAMS7200_DIRECTION]; + names[i] = dpe + ":_address.._datatype"; + values[i++] = configParameters[RAMS7200_DATATYPE]; + names[i] = dpe + ":_address.._subindex"; + values[i++] = configParameters[RAMS7200_SUBINDEX]; + + dpSetWait(names, values); +} diff --git a/winccoa/scripts/userDrivers.ctl b/winccoa/scripts/userDrivers.ctl new file mode 100644 index 0000000..d380ecf --- /dev/null +++ b/winccoa/scripts/userDrivers.ctl @@ -0,0 +1,72 @@ +////////////////////////////////////////////////////////////////////////////// +// If you want to include a new driver +// +// 1. In this script below +// add new item to dds[i] for names, types and drivers respectively below +// +// 2. In panels/para +// copy and change address_skeleton.pnl to create a new para-panel for +// a new driver +// panel name must be: address_newdrivertype.pnl +// (in our example below: address_tstdrv1.pnl) +// +// IMPORTANT: don't change the script in the panel-attributes and the buttons! +// +// 3. In scripts/userPara.ctl +// add new case selection ( in our example case "tstdrv1":) +// into the next four functions +// into scripts/userPara.ctl: +// upDpGetAddress +// upDpSetAddress +// upWritePanelAllAddressAttributes +// upReadPanelAllAddressAttributes +// and write the appropriate commands +// +// global variable used for the _address.. -attributes is +// anytype dpc; +// dpc[1]=reference; +// dpc[2]=subindex; +// dpc[3]=mode; +// dpc[4]=start; +// dpc[5]=interval; +// dpc[6]=reply; +// dpc[7]=datatype; +// dpc[8]=drv_ident; +// dpc[9]=driver; +// you dont't have to set all of them, use only the necessary elements! +////////////////////////////////////////////////////////////////////////////// +// +// be careful: always use the same number of driver elements +// (e.g. dyn_strings, cases, etc.) +// +////////////////////////////////////////////////////////////////////////////// +// The examples in this script use a copy of panels/para/address_sim.pnl +////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////// +// fill the makeDynString with the new driver datas +////////////////////////////////////////////////////////////////////////////// +dyn_dyn_string main() +{ + dyn_dyn_string dds; + + // names + // this text will be displayed in the driver type selection combobox in address.pnl + // Example: + dds[1]=makeDynString("RAMS7200 Driver"); + + + // types + // this text identifies the driver type. The panel name must have the name + // "address_"+typename+".pnl" and must be in panels/para + // Example: + dds[2]=makeDynString("rams7200"); + + // drivers + // dds[3]=makeDynString(); + // this text will be set in _address.._drv_ident + // Example: + dds[3]=makeDynString("RAMS7200"); + + return (dds); +} diff --git a/winccoa/scripts/userPara.ctl b/winccoa/scripts/userPara.ctl new file mode 100644 index 0000000..65198e8 --- /dev/null +++ b/winccoa/scripts/userPara.ctl @@ -0,0 +1,262 @@ +////////////////////////////////////////////////////////////////////////////// +// If you want to include a new driver: +// +// 1. In scripts/userDrivers.ctl +// add new item to dds[i] for names, types and drivers respectively below +// +// 2. In panels/para +// copy and change address_skeleton.pnl to create a new para-panel for +// a new driver +// panel name must be: address_newdrivertype.pnl +// (in our example below: address_tstdrv1.pnl) +// +// IMPORTANT: don't change the script in the panel-attributes and the buttons! +// +// 3. In this script below +// add new case selection ( in our example case "tstdrv1":) +// into the next four functions +// upDpGetAddress +// upDpSetAddress +// upWritePanelAllAddressAttributes +// upReadPanelAllAddressAttributes +// and write the appropriate commands +// +// global variable used for the _address.. -attributes is +// anytype dpc; +// dpc[1]=reference; +// dpc[2]=subindex; +// dpc[3]=mode; +// dpc[4]=start; +// dpc[5]=interval; +// dpc[6]=reply; +// dpc[7]=datatype; +// dpc[8]=drv_ident; +// dpc[9]=driver; +// you don't have to set all of them, use only the necessary elements! +////////////////////////////////////////////////////////////////////////////// +// +// be careful: always use the same number of driver elements +// (e.g. dyn_strings, cases, etc.) +// +////////////////////////////////////////////////////////////////////////////// +// The examples in this script use a copy of panels/para/address_sim.pnl +////////////////////////////////////////////////////////////////////////////// + +////////////////////////////////////////////////////////////////////////////// +// main calls the needed function +// fct = 1: upDpGetAddress +// fct = 2: upDpSetAddress +// fct = 3: upWritePanelAllAddressAttributes +// fct = 4: upReadPanelAllAddressAttributes +////////////////////////////////////////////////////////////////////////////// +anytype main(string dpe, int Id, anytype dpc, int fct) +{ + bool ok, all_right; + + switch (fct) + { + case 1: upDpGetAddress(dpe, Id, dpc); + break; + case 2: upDpSetAddress(dpe, Id, dpc, all_right); dpc[99]=all_right; + break; + case 3: upWritePanelAllAddressAttributes(dpe, Id, dpc); + break; + case 4: upReadPanelAllAddressAttributes(dpe, Id, dpc, all_right); dpc[99]=all_right; + break; + } + return (dpc); +} + +////////////////////////////////////////////////////////////////////////////// +// this function reads the datapoint values +////////////////////////////////////////////////////////////////////////////// +upDpGetAddress(string dpe, int Id, anytype &dpc) +{ + int datatype,driver,i,distrib_type; + bool all_right,active; + char mode; + time start,interval,reply; + string drv_ident,reference,config=paGetDpConfig(globalOpenConfig[Id]), + dpn=dpSubStr(dpe,DPSUB_DP)+".",pg,ser_nr; + unsigned subindex,offset; + + switch (globalAddressOld[Id]) + { + case "rams7200": + dpGet(dpe+":"+config+".._active",active, + dpe+":"+config+".._reference",reference, + dpe+":"+config+".._subindex",subindex, + dpe+":"+config+".._mode",mode, + dpe+":"+config+".._reply",reply, + dpe+":"+config+".._datatype",datatype, + //dpe+":"+config+".._poll_group",pg, + dpe+":"+config+".._drv_ident",drv_ident, + dpe+":_distrib.._driver",driver); + dpc[1]=reference; + dpc[2]=subindex; + dpc[3]=mode; + dpc[6]=reply; + dpc[7]=datatype; + dpc[8]=drv_ident; + if (driver<1) driver=1; + dpc[9]=driver; + dpc[11]=pg; + dpc[12]=active; + break; + default: break; + } +} + +////////////////////////////////////////////////////////////////////////////// +upDpSetAddress(string dpe, int Id, dyn_anytype dpc, bool &all_right) +{ + bool ok; + string config=paGetDpConfig(globalOpenConfig[Id]),dpn=dpSubStr(dpe,DPSUB_DP)+"."; + dyn_int drivers; + dyn_string sPara; + + switch (globalAddressOld[Id]) + { + case "rams7200": + paErrorHandlingDpSet( + dpSetWait(dpe+":_distrib.._driver",dpc[9]),all_right); + paErrorHandlingDpSet( + dpSetWait(dpe+":_address.._type", DPCONFIG_PERIPH_ADDR_MAIN, + dpe+":"+config+".._reference",dpc[1], + dpe+":"+config+".._subindex",dpc[2], + dpe+":"+config+".._mode",dpc[3], + dpe+":"+config+".._reply",dpc[6], + dpe+":"+config+".._datatype",dpc[7], + //dpe+":"+config+".._poll_group", dpc[11], + dpe+":"+config+".._drv_ident",dpc[8]),all_right); + paErrorHandlingDpSet( + dpSetWait(dpe+":_address.._active",dpc[12]),all_right); + break; + default: break; + } +} + +////////////////////////////////////////////////////////////////////////////// +upWritePanelAllAddressAttributes(string dpe, int Id, anytype dpc) +{ + int i,j=0,pos=1,trafoPos, + lowlevel,q,intern, + plc=0,comp=0,rack=0,slot=0,mode=0, + cbase=0,cfactor=1,ctime, + ibase=0,ifactor=0,icommand, + smooth=0,flutter=1, + art, df=0, m, m13; + bool err=false; + float itime; + string s,text,reference, pg; + dyn_int typ; + dyn_string ds,dss; + + switch (globalAddressOld[Id]) + { + case "rams7200": + if (dpc[3]>=64) { dpc[3]-=64; lowlevel=1;} + if (dpc[3]>=32) { dpc[3]-=32;} + if (dpc[3]<=0) dpc[3]=1; + if (dpc[3]==1 ||dpc[3]==5) + { + setMultiValue(//"lowlevel","visible",false, + "lowlevel", "state", 0,lowlevel); + setValue("einaus","number",0); + } + else if (dpc[3] >= 6) + { + setMultiValue("einaus","number",2, + //"lowlevel","visible",true, + "lowlevel", "state", 0,lowlevel); + } + else + { + setMultiValue("einaus","number",1, + //"lowlevel","visible",true, + "lowlevel", "state", 0,lowlevel); + } + + if (dpc[3] == 2 || dpc[3] == 6) + setMultiValue("inputmode","number",0); + else if (dpc[3] == 4 || dpc[3] == 7) + setMultiValue("inputmode","number",1); + else if (dpc[3] == 3 || dpc[3] == 8) + setMultiValue("inputmode","number",2); + //pg = dpc[11]; + //pg = strltrim(pg, "_"); + setMultiValue("cboAddressActive","state",0,dpc[12], + "reference","text",dpc[1], + "subindex","text",dpc[2], + //"pollgroup","text",pg, + "trans_art","selectedPos",dpc[7]-999, + "Treiber","text",dpc[9]); + break; + default: + break; + } +} + +////////////////////////////////////////////////////////////////////////////// +upReadPanelAllAddressAttributes(string dpe, int Id, dyn_anytype &dpc, bool &readOK) +{ + int pos,i,j,k,l,mode,n,o,p,driver,datatype, + lowlevel,q; + bool active; + string s,text,pg; + + readOK=true; + switch (globalAddressOld[Id]) + { + case "rams7200": + getMultiValue("cboAddressActive","state",0,active, + "trans_art","selectedPos",j, + "Treiber","text",driver, + "subindex","text",l, + "reference","text",s, + "einaus","number",p, + "inputmode","number",q, + //"pollgroup","text",pg, + "lowlevel","state",0,lowlevel); + // transformation + j = j+999; + + // mode + if (p == 0) + //Output + mode = 1; + else if (p == 1) + { + // Input + if (q == 0) + mode = 2; + else if (q == 1) + mode = 4; + else + mode = 3; + } + else + { + // In/Output + if (q == 0) + mode = 6; + else if (q == 1) + mode = 7; + else + mode = 8; + } + if (lowlevel) mode+=64; + + // fill the dyn_anytype + dpc[1]=s; + dpc[2]=l; + dpc[3]=mode; + dpc[7]=j; + dpc[8]=globalAddressDrivers[dynContains(globalAddressTypes,globalAddressNew[paMyModuleId()])]; + dpc[9]=driver; + dpc[11]= ""; //polling group + dpc[12]=active; + break; + default: break; + } +}