From 269c9c5586f4d80d9a606db31ed29ccca2522713 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 11:45:37 +0200 Subject: [PATCH 01/13] add minimum C++ version --- CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index ecca351..c01541d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,9 @@ #Setup the project project(restDAQ) + +set(CMAKE_CXX_STANDARD 17) + message("=============== ${PROJECT_NAME} ==============") set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake ${CMAKE_MODULE_PATH}) From f58bad4684c2ffcbdf1d4452aa522f1342287ff3 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 13:50:19 +0200 Subject: [PATCH 02/13] refactoring cmake --- CMakeLists.txt | 66 ++++++++++++++++------------- daq/CMakeLists.txt | 5 +-- daq/TRESTDAQ.h | 4 +- daq/TRESTDAQManager.cxx | 92 ++++++++++++++++++++--------------------- gui/CMakeLists.txt | 11 ++--- 5 files changed, 89 insertions(+), 89 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c01541d..23232a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,59 +5,65 @@ project(restDAQ) set(CMAKE_CXX_STANDARD 17) +if (${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + # this will only be accessed when build restG4 as a standalone package, not when building the framework + message(STATUS "${PROJECT_NAME} standalone build") + CMAKE_MINIMUM_REQUIRED(VERSION 3.16) + find_package(REST REQUIRED) + string(FIND ${REST_LIBRARIES} "RestRaw" REST_RAW_FOUND) + if (${REST_RAW_FOUND} EQUAL -1) + message(SEND_ERROR "REST found but 'RestRaw' library is not present. Please install REST with RawLib") + endif () +endif () + +message("-- Found REST version: ${REST_VERSION} with libraries: ${REST_LIBRARIES}") + message("=============== ${PROJECT_NAME} ==============") set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake ${CMAKE_MODULE_PATH}) # Find ROOT -find_package(ROOT REQUIRED COMPONENTS Gui) +find_package(ROOT REQUIRED COMPONENTS Gui CONFIG) execute_process(COMMAND root-config --cflags OUTPUT_VARIABLE ROOT_CFLAGS) string(STRIP ${ROOT_CFLAGS} ROOT_CFLAGS) message("-- Found ROOT version: ${ROOT_VERSION} with compilation flags: ${ROOT_CFLAGS} and libraries: ${ROOT_LIBRARIES}") #Find REST -IF(NOT DEFINED REST_PATH) - IF(DEFINED ENV{REST_PATH}) - set(REST_PATH $ENV{REST_PATH}) - ELSE() - message(FATAL_ERROR "ERROR ::: REST_PATH must be defined as an environment variable and point to REST install directory") - return() - ENDIF() -ENDIF() -set(CMAKE_INSTALL_PREFIX ${REST_PATH}) -message(STATUS "Using REST PATH: " ${REST_PATH}) +if (NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX ${REST_PATH}) +endif () + +message(STATUS "Package ${PROJECT_NAME} will be installed in ${CMAKE_INSTALL_PREFIX}") -message("-- Found REST version: ${REST_VERSION} with libraries: ${REST_LIBRARIES}") # TODO: Implement a check for '-lRestRaw' in ${REST_LIBRARIES} (and exit if not found) # Still if we use -DREST_DAQ=ON at the framework compilation it will enable RawLib by default -if (NOT CMAKE_CXX_FLAGS) - SET(CMAKE_CXX_FLAGS "-std=c++1y") # We should use the c++ flags from ${ROOT_CFLAGS} -endif () - #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- #Set include and lib -if(DEFINED rest_include_dirs) - set(incdir ${PROJECT_SOURCE_DIR}/include ${ROOT_INCLUDE_DIRS} ${rest_include_dirs}) -else() - set(incdir ${PROJECT_SOURCE_DIR}/include ${ROOT_INCLUDE_DIRS} ${REST_PATH}/include) -endif() +set(INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) -set(lnklib ${ROOT_LIBRARIES} RestRaw) -string(STRIP "${lnklib}" lnklib) +set(LINK_LIBRARIES ${ROOT_LIBRARIES} RestRaw) +string(STRIP "${LINK_LIBRARIES}" LINK_LIBRARIES) add_subdirectory(daq) add_subdirectory(gui) #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -#Add execuatable and link to restDAQ libraries -add_executable(restDAQManager restDAQManager.cxx) -target_link_libraries(restDAQManager LINK_PUBLIC RESTDAQ ${lnklib}) +#Add executable and link to restDAQ libraries + +set(EXECUTABLE_NAME restDAQManager) + +add_executable(${EXECUTABLE_NAME} restDAQManager.cxx) + +target_link_libraries(${EXECUTABLE_NAME} PUBLIC RESTDAQ ${LINK_LIBRARIES} ${ROOT_LIBRARIES} RestRaw) +target_include_directories(${EXECUTABLE_NAME} SYSTEM PUBLIC ${INCLUDE_DIRS}) + +message(STATUS "include directories: ${INCLUDE_DIRS}") #---------------------------------------------------------------------------- # Copy restDAQManager to the install directory -install(TARGETS restDAQManager DESTINATION bin) +install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin) #---------------------------------------------------------------------------- # Copy macros to the install directory @@ -68,6 +74,8 @@ INSTALL(FILES ${MAC} DESTINATION ./macros/daq) # Install the executable to 'bin' directory under CMAKE_INSTALL_PREFIX # #install(TARGETS ${PROJECT_NAME} DESTINATION bin) -set(package_added "${PROJECT_NAME}") -set(package_added ${package_added} PARENT_SCOPE) +if (NOT ${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + set(package_added "${PROJECT_NAME}") + set(package_added ${package_added} PARENT_SCOPE) +endif () diff --git a/daq/CMakeLists.txt b/daq/CMakeLists.txt index 193bf28..51698db 100644 --- a/daq/CMakeLists.txt +++ b/daq/CMakeLists.txt @@ -1,9 +1,8 @@ add_library(RESTDAQ SHARED TRESTDAQ.cxx TRESTDAQSocket.cxx DCCPacket.cxx TRESTDAQDCC.cxx FEMINOSPacket.cxx TRESTDAQFEMINOS.cxx TRESTDAQDummy.cxx TRESTDAQManager.cxx) -target_include_directories(RESTDAQ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${rest_include_dirs}) +target_include_directories(RESTDAQ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) -target_link_libraries(RESTDAQ ${lnklib} RestRaw) +target_link_libraries(RESTDAQ PUBLIC ${LINK_LIBRARIES} RestFramework RestRaw) install(TARGETS RESTDAQ DESTINATION lib) - diff --git a/daq/TRESTDAQ.h b/daq/TRESTDAQ.h index 36b6188..c7038ce 100644 --- a/daq/TRESTDAQ.h +++ b/daq/TRESTDAQ.h @@ -15,10 +15,10 @@ To implement generic methods here #include #include +#include "TRESTDAQException.h" #include "TRestRawDAQMetadata.h" #include "TRestRawSignalEvent.h" #include "TRestRun.h" -#include "TRESTDAQException.h" class TRESTDAQ { public: @@ -43,7 +43,7 @@ class TRESTDAQ { TRestRun* GetRestRun() { return restRun; } TRestRawSignalEvent* GetSignalEvent() { return fSignalEvent; } TRestRawDAQMetadata* GetDAQMetadata() { return daqMetadata; } - static void FillTree(TRestRun *rR, TRestRawSignalEvent* sEvent); + static void FillTree(TRestRun* rR, TRestRawSignalEvent* sEvent); private: TRestRun* restRun; diff --git a/daq/TRESTDAQManager.cxx b/daq/TRESTDAQManager.cxx index 346525b..f719f89 100644 --- a/daq/TRESTDAQManager.cxx +++ b/daq/TRESTDAQManager.cxx @@ -9,6 +9,8 @@ Control data acquisition via shared memory, should be always running #include "TRESTDAQManager.h" +#include + #include #include @@ -37,11 +39,10 @@ TRESTDAQManager::~TRESTDAQManager() { } void TRESTDAQManager::startUp() { + std::cout << __PRETTY_FUNCTION__ << std::endl; - std::cout<<__PRETTY_FUNCTION__<cfgFile)) { @@ -50,36 +51,34 @@ void TRESTDAQManager::startUp() { return; } - TRestRawDAQMetadata daqMetadata(sM->cfgFile); + TRestRawDAQMetadata daqMetadata(sM->cfgFile); - sM->status = 1; - DetachSharedMemory(&sM); + sM->status = 1; + DetachSharedMemory(&sM); - try{ - auto daq = GetTRESTDAQ(nullptr,&daqMetadata); - if(daq){ - daq->startUp(); - daq->stopDAQ(); - } - } catch(const TRESTDAQException& e) { - std::cerr<<"TRESTDAQException was thrown: "<startUp(); + daq->stopDAQ(); + } + } catch (const TRESTDAQException& e) { + std::cerr << "TRESTDAQException was thrown: " << e.what() << std::endl; } catch (const std::exception& e) { - std::cerr<<"std::exception was thrown: "< TRESTDAQManager::GetTRESTDAQ (TRestRun* rR, TRestRawDAQMetadata* dM){ +std::unique_ptr TRESTDAQManager::GetTRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM) { + std::unique_ptr daq(nullptr); - std::unique_ptr daq(nullptr); - - std::string electronicsType (dM->GetElectronicsType()); - auto eT = daq_metadata_types::electronicsTypes_map.find(electronicsType); + std::string electronicsType(dM->GetElectronicsType()); + auto eT = daq_metadata_types::electronicsTypes_map.find(electronicsType); if (eT == daq_metadata_types::electronicsTypes_map.end()) { std::cout << "Electronics type " << electronicsType << " not found, skipping " << std::endl; std::cout << "Valid electronics types:" << std::endl; for (const auto& [name, t] : daq_metadata_types::electronicsTypes_map) std::cout << (int)t << " " << name << std::endl; - return daq; + return daq; } if (eT->second == daq_metadata_types::electronicsTypes::DUMMY) { @@ -92,8 +91,7 @@ std::unique_ptr TRESTDAQManager::GetTRESTDAQ (TRestRun* rR, TRestRawDA std::cout << electronicsType << " not implemented, skipping..." << std::endl; } -return daq; - + return daq; } void TRESTDAQManager::dataTaking() { @@ -152,19 +150,19 @@ void TRESTDAQManager::dataTaking() { std::thread abrtT(AbortThread); - try{ - auto daq = GetTRESTDAQ(&restRun,&daqMetadata); - if(daq){ - TRESTDAQ::abrt = false; - daq->configure(); - std::cout << "Electronics configured, starting data taking run type " << std::endl; - daq->startDAQ(); // Should wait till completion or stopped - daq->stopDAQ(); + try { + auto daq = GetTRESTDAQ(&restRun, &daqMetadata); + if (daq) { + TRESTDAQ::abrt = false; + daq->configure(); + std::cout << "Electronics configured, starting data taking run type " << std::endl; + daq->startDAQ(); // Should wait till completion or stopped + daq->stopDAQ(); } - } catch(const TRESTDAQException& e) { - std::cerr<<"TRESTDAQException was thrown: "<exitManager; - if(sharedMemory->startUp == 1){ - DetachSharedMemory(&sharedMemory); - startUp(); - if (!GetSharedMemory(shmid, &sharedMemory)) break; - sharedMemory->startUp = 0; - sharedMemory->status = 0; + if (sharedMemory->startUp == 1) { + DetachSharedMemory(&sharedMemory); + startUp(); + if (!GetSharedMemory(shmid, &sharedMemory)) break; + sharedMemory->startUp = 0; + sharedMemory->status = 0; } if (sharedMemory->startDAQ == 1) { @@ -232,7 +230,7 @@ void TRESTDAQManager::run() { bool TRESTDAQManager::GetSharedMemory(int& sid, sharedMemoryStruct** sM, int flag, bool verbose) { if ((sid = shmget(TRESTDAQManager::key, sizeof(sharedMemoryStruct), flag)) == -1) { - if(verbose)std::cerr << "Error while creating shared memory (shmget) " << std::strerror(errno) << std::endl; + if (verbose) std::cerr << "Error while creating shared memory (shmget) " << std::strerror(errno) << std::endl; return false; } @@ -271,10 +269,10 @@ void TRESTDAQManager::InitializeSharedMemory(sharedMemoryStruct* sM) { sM->abortRun = 0; } -int TRESTDAQManager::GetFileSize(const std::string &filename){ - struct stat stat_buf; - int rc = stat(filename.c_str(), &stat_buf); - return rc == 0 ? stat_buf.st_size : -1; +int TRESTDAQManager::GetFileSize(const std::string& filename) { + struct stat stat_buf; + int rc = stat(filename.c_str(), &stat_buf); + return rc == 0 ? stat_buf.st_size : -1; } void TRESTDAQManager::AbortThread() { diff --git a/gui/CMakeLists.txt b/gui/CMakeLists.txt index bb44ddf..8cc0981 100644 --- a/gui/CMakeLists.txt +++ b/gui/CMakeLists.txt @@ -1,19 +1,14 @@ -#set( LibraryVersion "1.0" ) -#add_definitions(-DLIBRARY_VERSION="${LibraryVersion}") -#COMPILELIB("") +include_directories(${INCLUDE_DIRS}) -include_directories(${incdir}) - -find_package(ROOT 6.24 CONFIG REQUIRED) root_generate_dictionary(G__TRestDAQGUI TRestDAQGUI.h LINKDEF TRestDAQGUILinkDef.h) root_generate_dictionary(G__TRestDAQGUIMetadata TRestDAQGUIMetadata.h LINKDEF TRestDAQGUIMetadataLinkDef.h) add_library(RestDAQGUI SHARED TRestDAQGUIMetadata.cxx TRestDAQGUI.cxx G__TRestDAQGUI.cxx G__TRestDAQGUIMetadata.cxx) -target_include_directories(RestDAQGUI PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${rest_include_dirs}) +target_include_directories(RestDAQGUI PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) -target_link_libraries(RestDAQGUI RESTDAQ ${lnklib} -lpthread RestRaw) +target_link_libraries(RestDAQGUI PUBLIC RESTDAQ ${LINK_LIBRARIES} RestRaw) install(TARGETS RestDAQGUI DESTINATION lib) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libTRestDAQGUI_rdict.pcm DESTINATION lib) From b5b1005dfea023f375567d0544c45ff47e9a5e94 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 19:52:31 +0200 Subject: [PATCH 03/13] updated cli parsing logic --- CMakeLists.txt | 15 +++- daq/TRESTDAQManager.cxx | 14 +++- main.cxx | 166 ++++++++++++++++++++++++++++++++++++++++ restDAQManager.cxx | 153 ------------------------------------ 4 files changed, 189 insertions(+), 159 deletions(-) create mode 100644 main.cxx delete mode 100644 restDAQManager.cxx diff --git a/CMakeLists.txt b/CMakeLists.txt index 23232a8..c521e48 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,11 +52,22 @@ add_subdirectory(gui) #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- #Add executable and link to restDAQ libraries +include(FetchContent) + +# External dependencies +# cli11 (CLI parser) +FetchContent_Declare( + cli11 + GIT_REPOSITORY https://github.com/CLIUtils/CLI11.git + GIT_TAG v2.2.0 +) +FetchContent_MakeAvailable(cli11) + set(EXECUTABLE_NAME restDAQManager) -add_executable(${EXECUTABLE_NAME} restDAQManager.cxx) +add_executable(${EXECUTABLE_NAME} main.cxx) -target_link_libraries(${EXECUTABLE_NAME} PUBLIC RESTDAQ ${LINK_LIBRARIES} ${ROOT_LIBRARIES} RestRaw) +target_link_libraries(${EXECUTABLE_NAME} PUBLIC RESTDAQ RestDAQGUI ${LINK_LIBRARIES} ${ROOT_LIBRARIES} RestRaw PRIVATE CLI11::CLI11) target_include_directories(${EXECUTABLE_NAME} SYSTEM PUBLIC ${INCLUDE_DIRS}) message(STATUS "include directories: ${INCLUDE_DIRS}") diff --git a/daq/TRESTDAQManager.cxx b/daq/TRESTDAQManager.cxx index f719f89..bf6cef0 100644 --- a/daq/TRESTDAQManager.cxx +++ b/daq/TRESTDAQManager.cxx @@ -199,13 +199,17 @@ void TRESTDAQManager::run() { sharedMemoryStruct* sharedMemory; bool exitMan = false; do { - if (!GetSharedMemory(shmid, &sharedMemory)) break; + if (!GetSharedMemory(shmid, &sharedMemory)) { + break; + } exitMan = sharedMemory->exitManager; if (sharedMemory->startUp == 1) { DetachSharedMemory(&sharedMemory); startUp(); - if (!GetSharedMemory(shmid, &sharedMemory)) break; + if (!GetSharedMemory(shmid, &sharedMemory)) { + break; + } sharedMemory->startUp = 0; sharedMemory->status = 0; } @@ -218,7 +222,9 @@ void TRESTDAQManager::run() { dataTaking(); - if (!GetSharedMemory(shmid, &sharedMemory)) break; + if (!GetSharedMemory(shmid, &sharedMemory)) { + break; + } sharedMemory->status = 0; sharedMemory->startDAQ = 0; } @@ -279,7 +285,7 @@ void TRESTDAQManager::AbortThread() { int shmid; sharedMemoryStruct* sharedMemory; - bool abrt = 0; + bool abrt = false; do { if (!GetSharedMemory(shmid, &sharedMemory)) break; abrt = sharedMemory->abortRun; diff --git a/main.cxx b/main.cxx new file mode 100644 index 0000000..268380f --- /dev/null +++ b/main.cxx @@ -0,0 +1,166 @@ +#include +#include +#include + +#include +#include + +#include "CLI/App.hpp" +#include "CLI/Config.hpp" +#include "CLI/Formatter.hpp" +#include "TRESTDAQManager.h" + +using namespace std; +namespace fs = std::filesystem; + +constexpr char* thisProgram = "restDAQManager"; + +void signal_handler(int signum) { + cout << "Signal handler for '" << signum << "'" << endl; + TRESTDAQManager::ExitManager(); +} + +bool checkRunning() { + DIR* dir; + struct dirent* ent; + char* endptr; + + int nInstances = 0; + + if (!(dir = opendir("/proc"))) { + cerr << "Cannot open /proc" << endl; + return true; + } + + while ((ent = readdir(dir)) != nullptr) { + /* if endptr is not a null character, the directory is not + * entirely numeric, so ignore it */ + long lpid = strtol(ent->d_name, &endptr, 10); + if (*endptr != '\0') { + continue; + } + /* try to open the cmdline file */ + string fName = "/proc/" + to_string(lpid) + "/status"; + ifstream fin(fName, ifstream::in); + if (fin.fail()) { + cerr << "Cannot open " + fName + " skipping..." << endl; + continue; + } + + string line; + getline(fin, line); + stringstream str; + str << line; + string head, binary; + str >> head >> binary; + if (string(thisProgram).substr(0, 15) == binary) { + cout << binary << " pid: " << lpid << endl; + nInstances++; + } + fin.close(); + } + closedir(dir); + + return nInstances > 1; +} + +void initializeSignalHandler() { + signal(SIGINT, signal_handler); + signal(SIGQUIT, signal_handler); + signal(SIGILL, signal_handler); + signal(SIGTRAP, signal_handler); + signal(SIGABRT, signal_handler); + signal(SIGIOT, signal_handler); + signal(SIGFPE, signal_handler); + signal(SIGBUS, signal_handler); + signal(SIGSEGV, signal_handler); + signal(SIGKILL, signal_handler); + signal(SIGPIPE, signal_handler); + signal(SIGTERM, signal_handler); + signal(SIGSTKFLT, signal_handler); + signal(SIGSYS, signal_handler); +} + +int main(int argc, char** argv) { + CLI::App app{"REST DAQ"}; + + fs::path configFilename; + + CLI::App* gui = app.add_subcommand("gui", "Open the GUI. It will automatically connect to the acquisition process if it is running"); + gui->add_option("-c,--config", configFilename, "Configuration RML file for the GUI")->expected(1); + + CLI::App* run = app.add_subcommand("run", "Start acquisition process"); + run->add_option("-c,--config", configFilename, "Configuration RML file for the acquisition process")->expected(1); + string daqIP = "192.168.10.1"; // Default IP for 'feminos' card + run->add_option("--source,--ip", daqIP, "Hostname (IP) of the DAQ")->expected(1); + run->add_option("--stop", "Stop previous acquisition process if it exists")->expected(0); + run->add_option("--startup", "Perform startup of electronics")->expected(0); + run->add_option("--exit", "Perform startup of electronics")->expected(0); + + app.require_subcommand(1); + CLI11_PARSE(app, argc, argv); + + const auto subcommand = app.get_subcommands().back(); + const string subcommandName = subcommand->get_name(); + if (subcommandName == "gui") { + TApplication tApp("DAQ GUI", &argc, argv); + TRestDAQGUIMetadata* daqGuiMetadata; + if (configFilename.empty()) { + daqGuiMetadata = new TRestDAQGUIMetadata(); + } else { + daqGuiMetadata = new TRestDAQGUIMetadata(configFilename.string().c_str()); + } + new TRestDAQGUI(1000, 700, daqGuiMetadata); + + tApp.Run(); + } else if (subcommandName == "run") { + cout << "options: " << run->get_options().size() << endl; + if (!run->get_option("--exit")->empty()) { + cout << "Stopping existing acquisition process and exiting" << endl; + TRESTDAQManager::ExitManager(); + return 0; + } + if (!run->get_option("--stop")->empty()) { + cout << "Stopping existing acquisition process" << endl; + TRESTDAQManager::StopRun(); + } + if (checkRunning()) { + cout << "Another acquisition process is running but only one instance is allowed. Please close it before starting a new acquisition." + " You can close the existing process via the --stop flag" + << endl; + return 0; + } + + const bool startupElectronics = !run->get_option("--startup")->empty(); + + initializeSignalHandler(); + + TRESTDAQManager daqManager; + + if (!configFilename.empty()) { + int shareMemoryID; + TRESTDAQManager::sharedMemoryStruct* sharedMemory; + if (!TRESTDAQManager::GetSharedMemory(shareMemoryID, &sharedMemory)) { + cerr << "Cannot get shared memory!!" << endl; + return 1; + } + char* fullPath = realpath(configFilename.c_str(), nullptr); + if (fullPath) { + cout << "Full path: " << fullPath << endl; + sprintf(sharedMemory->cfgFile, "%s", fullPath); + } else { + sprintf(sharedMemory->cfgFile, "%s", configFilename.c_str()); + } + TRESTDAQManager::DetachSharedMemory(&sharedMemory); + if (startupElectronics) { + cout << "Attempting electronics startup" << endl; + daqManager.startUp(); + } else { + daqManager.dataTaking(); + } + } else { + cout << "Starting infinite loop" << endl; + daqManager.run(); + } + } +} diff --git a/restDAQManager.cxx b/restDAQManager.cxx deleted file mode 100644 index d937dbe..0000000 --- a/restDAQManager.cxx +++ /dev/null @@ -1,153 +0,0 @@ -#include -#include - -#include - -#include "TRESTDAQManager.h" - -const std::string thisProgram = "restDAQManager"; - -void signal_handler(int signum) { - std::cout << " signal handler " << signum << std::endl; - TRESTDAQManager::ExitManager(); -} - -void help() { - std::cout << " Rest DAQ Manager options:" << std::endl; - std::cout << " --e : Exit manager" << std::endl; - std::cout << " --s : Stop run (if ongoing)" << std::endl; - std::cout << " --c : Set configFile (single run)" << std::endl; - std::cout << " --h : Print this help" << std::endl; - std::cout << "If no arguments are provided it starts at infinite loop which is controller via shared memory" << std::endl; -} - -bool checkRunning() { - DIR* dir; - struct dirent* ent; - char* endptr; - - int nInstances = 0; - - if (!(dir = opendir("/proc"))) { - std::cerr << "Cannot open /proc" << std::endl; - return true; - } - - while ((ent = readdir(dir)) != NULL) { - /* if endptr is not a null character, the directory is not - * entirely numeric, so ignore it */ - long lpid = strtol(ent->d_name, &endptr, 10); - if (*endptr != '\0') { - continue; - } - /* try to open the cmdline file */ - std::string fName = "/proc/" + std::to_string(lpid) + "/status"; - std::ifstream fin(fName, std::ifstream::in); - if (fin.fail()) { - std::cerr << "Cannot open " + fName + " skipping..." << std::endl; - continue; - } - - std::string line; - std::getline(fin, line); - std::stringstream str; - str << line; - std::string head, binary; - str >> head >> binary; - if (thisProgram.substr(0, 15) == binary) { - std::cout << binary << " pid: " << lpid << std::endl; - nInstances++; - } - fin.close(); - } - closedir(dir); - - if (nInstances > 1) return true; - - return false; -} - -int main(int argc, char** argv) { - - std::string cfgFile = ""; - bool startUp = false; - - for (int i = 1; i < argc; i++) { - std::string arg = argv[i]; - std::cout<cfgFile, fullPath); - } else { - sprintf(mem->cfgFile, cfgFile.c_str()); - } - TRESTDAQManager::DetachSharedMemory(&mem); - if(startUp){ - std::cout<<"Trying startup"< Date: Wed, 26 Oct 2022 19:56:44 +0200 Subject: [PATCH 04/13] remove macros --- macros/REST_DAQGUI.C | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 macros/REST_DAQGUI.C diff --git a/macros/REST_DAQGUI.C b/macros/REST_DAQGUI.C deleted file mode 100644 index a395ce1..0000000 --- a/macros/REST_DAQGUI.C +++ /dev/null @@ -1,9 +0,0 @@ - -#include "TRestDAQGUI.h" - -void REST_DAQGUI(const std::string &inputRMLFile) { - - TRestDAQGUIMetadata *mt = new TRestDAQGUIMetadata(inputRMLFile.c_str()); - new TRestDAQGUI(1000, 700, mt); - -} From c4e272f072ac44fc3f86de75afe81d3c21c365f1 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 19:56:56 +0200 Subject: [PATCH 05/13] change executable name to `restDAQ` --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c521e48..7488ee6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,7 +63,7 @@ FetchContent_Declare( ) FetchContent_MakeAvailable(cli11) -set(EXECUTABLE_NAME restDAQManager) +set(EXECUTABLE_NAME restDAQ) add_executable(${EXECUTABLE_NAME} main.cxx) From afb8bef481fd32bf48adecc637ae032ab538fa7e Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 19:57:05 +0200 Subject: [PATCH 06/13] formatting rml examples --- examples/DAQGUI.rml | 2 +- examples/dummyDAQ.rml | 139 +++++++++++++++++++++--------------------- 2 files changed, 69 insertions(+), 72 deletions(-) diff --git a/examples/DAQGUI.rml b/examples/DAQGUI.rml index a78c9ec..5eefe4d 100644 --- a/examples/DAQGUI.rml +++ b/examples/DAQGUI.rml @@ -3,7 +3,7 @@ - + diff --git a/examples/dummyDAQ.rml b/examples/dummyDAQ.rml index debd2c5..80188e1 100644 --- a/examples/dummyDAQ.rml +++ b/examples/dummyDAQ.rml @@ -2,76 +2,73 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - From 85701c6c049c0cf7cf246cebb7f8ee9aea05fc63 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 20:01:26 +0200 Subject: [PATCH 07/13] .clang-format formatting and correct typos --- daq/DCCPacket.cxx | 44 +-- daq/DCCPacket.h | 116 +++--- daq/FEMINOSPacket.cxx | 703 ++++++++++++++++++------------------ daq/FEMINOSPacket.h | 198 +++++----- daq/TRESTDAQ.cxx | 34 +- daq/TRESTDAQ.h | 7 +- daq/TRESTDAQDCC.cxx | 138 +++---- daq/TRESTDAQDCC.h | 10 +- daq/TRESTDAQDummy.cxx | 2 +- daq/TRESTDAQException.h | 20 +- daq/TRESTDAQFEMINOS.cxx | 689 +++++++++++++++++------------------ daq/TRESTDAQFEMINOS.h | 47 ++- daq/TRESTDAQManager.h | 6 +- daq/TRESTDAQSocket.cxx | 36 +- daq/TRESTDAQSocket.h | 11 +- gui/TRestDAQGUI.cxx | 168 ++++----- gui/TRestDAQGUI.h | 33 +- gui/TRestDAQGUIMetadata.cxx | 64 ++-- gui/TRestDAQGUIMetadata.h | 24 +- 19 files changed, 1147 insertions(+), 1203 deletions(-) diff --git a/daq/DCCPacket.cxx b/daq/DCCPacket.cxx index 2899c23..54cd748 100644 --- a/daq/DCCPacket.cxx +++ b/daq/DCCPacket.cxx @@ -3,31 +3,28 @@ #include -void DCCPacket::DataPacket_Print( DataPacket *pck){ - - +void DCCPacket::DataPacket_Print(DataPacket* pck) { // DCC data packet has a different structure if (GET_FRAME_TY_V2(ntohs(pck->dcchdr)) & FRAME_TYPE_DCC_DATA) { DCC_Data_Print((EndOfEventPacket*)pck); return; - } // FEM data - Pedestal Histogram Mathematics + } // FEM data - Pedestal Histogram Mathematics else if (GET_TYPE(ntohs(pck->hdr)) == RESP_TYPE_HISTOSTAT) { Pedestal_PrintHistoMathPacket((PedestalHistoMathPacket*)pck); return; - } // FEM data - Pedestal Histogram Bins + } // FEM data - Pedestal Histogram Bins else if (GET_TYPE(ntohs(pck->hdr)) == RESP_TYPE_HISTOGRAM) { Pedestal_PrintHistoBinPacket((PedestalHistoBinPacket*)pck); return; - } // FEM data - Pedestal Histogram Summary + } // FEM data - Pedestal Histogram Summary else if (GET_TYPE(ntohs(pck->hdr)) == RESP_TYPE_HISTOSUMMARY) { Pedestal_PrintHistoSummaryPacket((PedestalHistoSummaryPacket*)pck); return; - } // FEM data - ADC samples in zero-suppressed or non zero-suppressed mode + } // FEM data - ADC samples in zero-suppressed or non zero-suppressed mode else if (GET_TYPE(ntohs(pck->hdr)) == RESP_TYPE_ADC_DATA) { FemAdcDataPrint(pck); return; } - } void DCCPacket::DCC_Data_Print(EndOfEventPacket* pck) { @@ -43,7 +40,7 @@ void DCCPacket::DCC_Data_Print(EndOfEventPacket* pck) { } else { - printf("DCC_Data_Print: unknown frame type 0x%x\n", GET_FRAME_TY_V2(ntohs(pck->dcchdr) ) ); + printf("DCC_Data_Print: unknown frame type 0x%x\n", GET_FRAME_TY_V2(ntohs(pck->dcchdr))); } } @@ -82,20 +79,18 @@ void DCCPacket::DCC_Histogram_Print(HistogramPacket* pck) { printf("------------------------------------\n"); } - void DCCPacket::EndOfEvent_PrintPacket(EndOfEventPacket* eop) { int i; printf("------------------------------------\r\n"); printf("Message size : %d bytes\r\n", ntohs(eop->size)); printf("DCC Header: Type:0x%x DCC_index:0x%x FEM_index:0x%x\r\n", GET_FRAME_TY_V2(ntohs(eop->dcchdr)), GET_DCC_INDEX(ntohs(eop->dcchdr)), - GET_FEM_INDEX(ntohs(eop->dcchdr))); + GET_FEM_INDEX(ntohs(eop->dcchdr))); printf("FEM Header: 0x%x\r\n", ntohs(eop->hdr)); for (i = 0; i < MAX_NB_OF_FEM_PER_DCC; i++) { printf("Fem(%2d) : recv: %d bytes sent: %d bytes\r\n", i, ntohl(eop->byte_rcv[i]), ntohl(eop->byte_snd[i])); } printf("Total : recv: %d bytes sent: %d bytes\r\n", ntohl(eop->tot_byte_rcv), ntohl(eop->tot_byte_snd)); - } /******************************************************************************* @@ -105,10 +100,10 @@ void DCCPacket::Pedestal_PrintHistoMathPacket(PedestalHistoMathPacket* phm) { printf("------------------------------------\n"); printf("Message size : %d bytes\n", ntohs(phm->size)); printf("DCC Header: Type:0x%x DCC_index:0x%x FEM_index:0x%x\n", GET_FRAME_TY_V2(ntohs(phm->dcchdr)), GET_DCC_INDEX(ntohs(phm->dcchdr)), - GET_FEM_INDEX(ntohs(phm->dcchdr))); + GET_FEM_INDEX(ntohs(phm->dcchdr))); printf("FEM Header: 0x%x\n", ntohs(phm->hdr)), printf("Read-back : Mode:%d Compress:%d Arg1:0x%x Arg2:0x%x\n", GET_RB_MODE(ntohs(phm->args)), GET_RB_COMPRESS(ntohs(phm->args)), - GET_RB_ARG1(ntohs(phm->args)), GET_RB_ARG2(ntohs(phm->args))); + GET_RB_ARG1(ntohs(phm->args)), GET_RB_ARG2(ntohs(phm->args))); printf("Bin min : %d\n", ntohs(phm->min_bin)); printf("Bin max : %d\n", ntohs(phm->max_bin)); @@ -135,7 +130,7 @@ void DCCPacket::Pedestal_PrintHistoBinPacket(PedestalHistoBinPacket* pck) { printf("------------------------------------\n"); printf("Message size : %d bytes\n", ntohs(pck->size)); printf("DCC Header : Type:0x%x DCC_index:0x%x FEM_index:0x%x\n", GET_FRAME_TY_V2(ntohs(pck->dcchdr)), GET_DCC_INDEX(ntohs(pck->dcchdr)), - GET_FEM_INDEX(ntohs(pck->dcchdr))); + GET_FEM_INDEX(ntohs(pck->dcchdr))); printf("FEM Header : Msg_type:0x%x Index:0x%x\n", GET_RESP_TYPE(ntohs(pck->hdr))); printf("Read-back : Arg1:0x%x Arg2:0x%x\n", GET_RB_ARG1(ntohs(pck->args)), GET_RB_ARG2(ntohs(pck->args))); @@ -165,7 +160,7 @@ void DCCPacket::Pedestal_PrintHistoSummaryPacket(PedestalHistoSummaryPacket* pck printf("------------------------------------\n"); printf("Message size : %d bytes\n", ntohs(pck->size)); printf("DCC Header : Type:0x%x DCC_index:0x%x FEM_index:0x%x\n", GET_FRAME_TY_V2(ntohs(pck->dcchdr)), GET_DCC_INDEX(ntohs(pck->dcchdr)), - GET_FEM_INDEX(ntohs(pck->dcchdr))); + GET_FEM_INDEX(ntohs(pck->dcchdr))); printf("FEM Header : Msg_type:0x%x Index:0x%x\n", GET_RESP_TYPE(ntohs(pck->hdr))); printf("Read-back : Arg1:0x%x Arg2:0x%x\n", GET_RB_ARG1(ntohs(pck->args)), GET_RB_ARG2(ntohs(pck->args))); @@ -180,7 +175,7 @@ void DCCPacket::Pedestal_PrintHistoSummaryPacket(PedestalHistoSummaryPacket* pck for (i = 0; i < (nbsw / 2); i++) { printf("Stat (%3d) : mean = %.2f stdev = %.2f\n", i, ((double)(ntohs(pck->stat[i].mean))) / 100.0, - ((double)(ntohs(pck->stat[i].stdev))) / 100.0); + ((double)(ntohs(pck->stat[i].stdev))) / 100.0); } printf("------------------------------------\n"); } @@ -200,21 +195,21 @@ void DCCPacket::FemAdcDataPrint(DataPacket* pck) { printf("------------------------------------\n"); printf("Packet sz : %d bytes\n", (ntohs(pck->size))); printf("DCC Header: Type:0x%x DCC_index:0x%x FEM_index:0x%x\n", GET_FRAME_TY_V2(ntohs(pck->dcchdr)), GET_DCC_INDEX(ntohs(pck->dcchdr)), - GET_FEM_INDEX(ntohs(pck->dcchdr))); + GET_FEM_INDEX(ntohs(pck->dcchdr))); printf("FEM Header: Msg_type:0x%x Index:0x%x\n", GET_RESP_TYPE(ntohs(pck->hdr)), GET_RESP_INDEX(ntohs(pck->hdr))); printf("Errors : FEC:0x%x Unable to SYNCH:%d Framing LOS:%d\n", GET_FEC_ERROR(ntohs(pck->hdr)), GET_SYNCH_FAIL(ntohs(pck->hdr)), - GET_LOS_FLAG(ntohs(pck->hdr))); + GET_LOS_FLAG(ntohs(pck->hdr))); printf("Read-back : Mode:%d Compress:%d Arg1:0x%x Arg2:0x%x\n", GET_RB_MODE(ntohs(pck->args)), GET_RB_COMPRESS(ntohs(pck->args)), - GET_RB_ARG1(ntohs(pck->args)), GET_RB_ARG2(ntohs(pck->args))); + GET_RB_ARG1(ntohs(pck->args)), GET_RB_ARG2(ntohs(pck->args))); - Arg12ToFecAsicChannel((unsigned short)GET_RB_ARG1(ntohs(pck->args)), (unsigned short)GET_RB_ARG2(ntohs(pck->args)), fec, asic,channel); + Arg12ToFecAsicChannel((unsigned short)GET_RB_ARG1(ntohs(pck->args)), (unsigned short)GET_RB_ARG2(ntohs(pck->args)), fec, asic, channel); printf(" Fec:%d Asic:%d Channel:%d\n", fec, asic, channel); ts = (((int)ntohs((pck->ts_h))) << 16) | (int)ntohs((pck->ts_l)); printf("Event : Type:%d Count:%d Time:0x%x NbOfWords:%d\n", GET_EVENT_TYPE(ntohs(pck->ecnt)), GET_EVENT_COUNT(ntohs(pck->ecnt)), ts, - ntohs(pck->scnt)); + ntohs(pck->scnt)); scnt = ntohs(pck->scnt) & 0x7FF; // Compute the number of short words in the packet @@ -247,8 +242,7 @@ void DCCPacket::FemAdcDataPrint(DataPacket* pck) { /******************************************************************************* Arg12ToFecAsicChannel *******************************************************************************/ -int DCCPacket::Arg12ToFecAsicChannel(unsigned short arg1, unsigned short arg2, unsigned short &fec, unsigned short &asic, unsigned short &channel) { - +int DCCPacket::Arg12ToFecAsicChannel(unsigned short arg1, unsigned short arg2, unsigned short& fec, unsigned short& asic, unsigned short& channel) { fec = (10 * (arg1 % 6) / 2 + arg2) / 4; asic = (10 * (arg1 % 6) / 2 + arg2) % 4; channel = arg1 / 6; @@ -279,5 +273,3 @@ int DCCPacket::Arg12ToFecAsicChannel(unsigned short arg1, unsigned short arg2, u return physChannel; } - - diff --git a/daq/DCCPacket.h b/daq/DCCPacket.h index 68660f7..d85082d 100644 --- a/daq/DCCPacket.h +++ b/daq/DCCPacket.h @@ -1,8 +1,8 @@ #ifndef DCC_PACKET_H #define DCC_PACKET_H -#include #include +#include #define MAX_ETH_PACKET_DATA_SIZE 4096 @@ -48,46 +48,46 @@ #define GET_SAMPLE_COUNT(word) (((word)&0x0FFF)) // Macros to manipulate DataPacket DCC header -#define FRAME_TYPE_FEM_DATA 0x0000 -#define FRAME_TYPE_DCC_DATA 0x0001 -#define FRAME_FLAG_EORQ 0x0004 -#define FRAME_FLAG_EOEV 0x0008 -#define GET_FEM_INDEX(word) (((word) & 0x000F)>>0) -#define GET_DCC_INDEX(word) (((word) & 0x03F0)>>4) -#define GET_FRAME_TY_V2(word) (((word) & 0x3C00)>>10) -#define PUT_FEM_INDEX(word, ix) (((word) & 0xFFF0) | (((ix) & 0x000F) << 0)) -#define PUT_DCC_INDEX(word, ix) (((word) & 0xFC0F) | (((ix) & 0x003F) << 4)) -#define PUT_FRAME_TY_V2(word, ty) (((word) & 0x03FF) | FRAME_HDR_V2 | (((ty) & 0x000F) <<10)) +#define FRAME_TYPE_FEM_DATA 0x0000 +#define FRAME_TYPE_DCC_DATA 0x0001 +#define FRAME_FLAG_EORQ 0x0004 +#define FRAME_FLAG_EOEV 0x0008 +#define GET_FEM_INDEX(word) (((word)&0x000F) >> 0) +#define GET_DCC_INDEX(word) (((word)&0x03F0) >> 4) +#define GET_FRAME_TY_V2(word) (((word)&0x3C00) >> 10) +#define PUT_FEM_INDEX(word, ix) (((word)&0xFFF0) | (((ix)&0x000F) << 0)) +#define PUT_DCC_INDEX(word, ix) (((word)&0xFC0F) | (((ix)&0x003F) << 4)) +#define PUT_FRAME_TY_V2(word, ty) (((word)&0x03FF) | FRAME_HDR_V2 | (((ty)&0x000F) << 10)) // We now support the old and new version of the data packet structure #define FRAME_HDR_V2_FIELD 0xC000 -#define FRAME_HDR_V2 0x4000 -#define IS_DATA_PACKET_V2(word) (((word) & FRAME_HDR_V2_FIELD) == FRAME_HDR_V2) +#define FRAME_HDR_V2 0x4000 +#define IS_DATA_PACKET_V2(word) (((word)&FRAME_HDR_V2_FIELD) == FRAME_HDR_V2) -//Miscellanea +// Miscellanea #define MAX_NB_OF_FEM_PER_DCC 6 -#define MAX_EVENT_SIZE 6 * 4 * 79 * 2 * (512 + 32)*12 +#define MAX_EVENT_SIZE 6 * 4 * 79 * 2 * (512 + 32) * 12 #define BHISTO_SIZE 256 #define PHISTO_SIZE 512 #define ASIC_MAX_CHAN_INDEX 78 namespace DCCPacket { - // New structure of DataPacket. Aliased to DataPacketV2 - typedef struct { - unsigned short size; // size in bytes including the size of the size field itself - unsigned short dcchdr; // specific header added by the DCC - unsigned short hdr; // specific header put by the FEM - unsigned short args; // read-back arguments echoed by FEM - unsigned short ts_h; // local FEM timestamp MSB - unsigned short ts_l; // local FEM timestamp LSB - unsigned short ecnt; // local FEM event type/count - unsigned short scnt; // sample count in first pulse over thr or total sample count in packet - unsigned short samp[MAX_ETH_PACKET_DATA_SIZE/(sizeof(unsigned short))]; // data storage area - } DataPacket; - - // End of Event Packet - typedef struct { +// New structure of DataPacket. Aliased to DataPacketV2 +typedef struct { + unsigned short size; // size in bytes including the size of the size field itself + unsigned short dcchdr; // specific header added by the DCC + unsigned short hdr; // specific header put by the FEM + unsigned short args; // read-back arguments echoed by FEM + unsigned short ts_h; // local FEM timestamp MSB + unsigned short ts_l; // local FEM timestamp LSB + unsigned short ecnt; // local FEM event type/count + unsigned short scnt; // sample count in first pulse over thr or total sample count in packet + unsigned short samp[MAX_ETH_PACKET_DATA_SIZE / (sizeof(unsigned short))]; // data storage area +} DataPacket; + +// End of Event Packet +typedef struct { unsigned short size; // size in bytes including the size of the size field itself unsigned short dcchdr; // specific header added by the DCC unsigned short hdr; // specific header similar to what is put by the FEM @@ -96,9 +96,9 @@ namespace DCCPacket { unsigned int byte_snd[MAX_NB_OF_FEM_PER_DCC]; // data sent per FEM unsigned int tot_byte_rcv; unsigned int tot_byte_snd; - } EndOfEventPacket; +} EndOfEventPacket; - typedef struct { +typedef struct { unsigned short size; // size in bytes including the size of the size field itself unsigned short dcchdr; // specific header added by the DCC unsigned short hdr; // placeholder for header normally put by FEM @@ -113,25 +113,25 @@ namespace DCCPacket { unsigned short pad; // padding for 32-bit alignment unsigned int entries; // number of entries unsigned short samp[BHISTO_SIZE]; // data storage area - } HistogramPacket; +} HistogramPacket; - typedef struct { +typedef struct { unsigned short mean; // mean of channel pedestal unsigned short stdev; // standard deviation of channel pedestal - } channel_stat; +} channel_stat; - // Histogram data packet for pedestals - typedef struct { +// Histogram data packet for pedestals +typedef struct { unsigned short size; // size in bytes including the size of the size field itself unsigned short dcchdr; // specific header added by the DCC unsigned short hdr; // specific header inherited from FEM unsigned short args; // read-back arguments as encoded by FEM unsigned short scnt; // number of unsigned short filled in following array channel_stat stat[ASIC_MAX_CHAN_INDEX + 1]; // summary of statistics for current ASIC - } PedestalHistoSummaryPacket; +} PedestalHistoSummaryPacket; - // Histogram data packet for pedestals - typedef struct { +// Histogram data packet for pedestals +typedef struct { unsigned short size; // size in bytes including the size of the size field itself unsigned short dcchdr; // specific header added by the DCC unsigned short hdr; // specific header put by the FEM @@ -147,10 +147,10 @@ namespace DCCPacket { unsigned int entries; // number of entries unsigned short bin_sat; // number of bins saturated unsigned short align; // alignment - } PedestalHistoMathPacket; +} PedestalHistoMathPacket; - // New structure of DataPacket. Aliased to DataPacketV2 - typedef struct { +// New structure of DataPacket. Aliased to DataPacketV2 +typedef struct { unsigned short size; // size in bytes including the size of the size field itself unsigned short dcchdr; // specific header added by the DCC unsigned short hdr; // specific header put by the FEM @@ -160,20 +160,20 @@ namespace DCCPacket { unsigned short ecnt; // local FEM event type/count unsigned short scnt; // sample count in first pulse over thr or total sample count in packet unsigned short samp[PHISTO_SIZE]; // data storage area - } PedestalHistoBinPacket; - - enum class packetReply { ERROR = -1, RETRY = 0, OK = 1 }; - enum class packetType { ASCII = 0, BINARY = 1 }; - - void DataPacket_Print( DataPacket *pck); - void DCC_Data_Print(EndOfEventPacket* pck); - void DCC_Histogram_Print(HistogramPacket* pck); - void EndOfEvent_PrintPacket(EndOfEventPacket* eop); - void Pedestal_PrintHistoMathPacket(PedestalHistoMathPacket* phm); - void Pedestal_PrintHistoBinPacket(PedestalHistoBinPacket* pck); - void Pedestal_PrintHistoSummaryPacket(PedestalHistoSummaryPacket* pck); - void FemAdcDataPrint(DataPacket* pck); - int Arg12ToFecAsicChannel(unsigned short arg1, unsigned short arg2, unsigned short &fec, unsigned short &asic, unsigned short &channel); -} +} PedestalHistoBinPacket; + +enum class packetReply { ERROR = -1, RETRY = 0, OK = 1 }; +enum class packetType { ASCII = 0, BINARY = 1 }; + +void DataPacket_Print(DataPacket* pck); +void DCC_Data_Print(EndOfEventPacket* pck); +void DCC_Histogram_Print(HistogramPacket* pck); +void EndOfEvent_PrintPacket(EndOfEventPacket* eop); +void Pedestal_PrintHistoMathPacket(PedestalHistoMathPacket* phm); +void Pedestal_PrintHistoBinPacket(PedestalHistoBinPacket* pck); +void Pedestal_PrintHistoSummaryPacket(PedestalHistoSummaryPacket* pck); +void FemAdcDataPrint(DataPacket* pck); +int Arg12ToFecAsicChannel(unsigned short arg1, unsigned short arg2, unsigned short& fec, unsigned short& asic, unsigned short& channel); +} // namespace DCCPacket #endif diff --git a/daq/FEMINOSPacket.cxx b/daq/FEMINOSPacket.cxx index ee68dff..1023b0b 100644 --- a/daq/FEMINOSPacket.cxx +++ b/daq/FEMINOSPacket.cxx @@ -1,375 +1,382 @@ #include +#include #include -#include -void FEMINOSPacket::DataPacket_Print (uint16_t *fr, const uint16_t &size){ - - int sz_rd=0,si=0; - uint16_t r0, r1, r2, r3; - - do { - if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HIT_IX){ - r0 = GET_CARD_IX(*fr); - r1 = GET_CHIP_IX(*fr); - r2 = GET_CHAN_IX(*fr); - printf("Card %02d Chip %01d Channel %02d\n", r0, r1, r2); - fr++; - sz_rd++; - si=0; - } else if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HIT_CNT){ - r0 = GET_CARD_IX(*fr); - r1 = GET_CHIP_IX(*fr); - r2 = GET_CHAN_IX(*fr); - printf( "Card %02d Chip %01d Channel_Hit_Count %02d\n", r0, r1, r2); - fr++; - sz_rd++; - } else if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HISTO){ - r0 = GET_CARD_IX(*fr); - r1 = GET_CHIP_IX(*fr); - r2 = GET_CHAN_IX(*fr); - printf( "Card %02d Chip %01d Channel_Histo_Index %02d\n", r0, r1, r2); - fr++; - sz_rd++; - } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE) { - r0 = GET_ADC_DATA(*fr); - printf("%03d 0x%04x (%4d)\n", si, r0, r0); - fr++; - sz_rd++; - si++; - } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_LAT_HISTO_BIN) { - r0 = GET_LAT_HISTO_BIN(*fr); - fr++; - sz_rd++; - uint32_t tmp = GetUInt32FromBufferInv(fr, sz_rd);fr+=2; - printf("%03d %03d\n", r0, tmp); - } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_CHIP_LAST_CELL_READ){ - for(int i=0;i<4;i++){ - printf( "Chip %01d Last_Cell_Read %03d (0x%03x)\n",GET_LST_READ_CELL_CHIP_IX(*fr), GET_LST_READ_CELL(*fr), GET_LST_READ_CELL(*fr)); - fr++; - sz_rd++; - } - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_TIME_BIN_IX) { - r0 = GET_TIME_BIN(*fr); - printf("Time_Bin: %d\n", r0); - fr++; - sz_rd++; - si = 0; - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_HISTO_BIN_IX){ - r0 = GET_HISTO_BIN(*fr); - fr++; - sz_rd++; - printf("Bin %3d Val %5d\n", r0, *fr); - fr++; - sz_rd++; - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_PEDTHR_LIST){ - r0 = GET_PEDTHR_LIST_FEM(*fr); - r1 = GET_PEDTHR_LIST_ASIC(*fr); - r2 = GET_PEDTHR_LIST_MODE(*fr); - r3 = GET_PEDTHR_LIST_TYPE(*fr); - fr++; - sz_rd++; - - if (r3 == 0){ // pedestal entry - printf("# Pedestal List for FEM %02d ASIC %01d\n", r0, r1); - } else { - printf("# Threshold List for FEM %02d ASIC %01d\n", r0, r1); - } - printf("fem %02d\n", r0); - if(r2==0){ //AGET - r2 = 71; - } else { - r2 = 78; - } +void FEMINOSPacket::DataPacket_Print(uint16_t* fr, const uint16_t& size) { + int sz_rd = 0, si = 0; + uint16_t r0, r1, r2, r3; + + do { + if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HIT_IX) { + r0 = GET_CARD_IX(*fr); + r1 = GET_CHIP_IX(*fr); + r2 = GET_CHAN_IX(*fr); + printf("Card %02d Chip %01d Channel %02d\n", r0, r1, r2); + fr++; + sz_rd++; + si = 0; + } else if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HIT_CNT) { + r0 = GET_CARD_IX(*fr); + r1 = GET_CHIP_IX(*fr); + r2 = GET_CHAN_IX(*fr); + printf("Card %02d Chip %01d Channel_Hit_Count %02d\n", r0, r1, r2); + fr++; + sz_rd++; + } else if ((*fr & PFX_14_BIT_CONTENT_MASK) == PFX_CARD_CHIP_CHAN_HISTO) { + r0 = GET_CARD_IX(*fr); + r1 = GET_CHIP_IX(*fr); + r2 = GET_CHAN_IX(*fr); + printf("Card %02d Chip %01d Channel_Histo_Index %02d\n", r0, r1, r2); + fr++; + sz_rd++; + } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE) { + r0 = GET_ADC_DATA(*fr); + printf("%03d 0x%04x (%4d)\n", si, r0, r0); + fr++; + sz_rd++; + si++; + } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_LAT_HISTO_BIN) { + r0 = GET_LAT_HISTO_BIN(*fr); + fr++; + sz_rd++; + uint32_t tmp = GetUInt32FromBufferInv(fr, sz_rd); + fr += 2; + printf("%03d %03d\n", r0, tmp); + } else if ((*fr & PFX_12_BIT_CONTENT_MASK) == PFX_CHIP_LAST_CELL_READ) { + for (int i = 0; i < 4; i++) { + printf("Chip %01d Last_Cell_Read %03d (0x%03x)\n", GET_LST_READ_CELL_CHIP_IX(*fr), GET_LST_READ_CELL(*fr), GET_LST_READ_CELL(*fr)); + fr++; + sz_rd++; + } + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_TIME_BIN_IX) { + r0 = GET_TIME_BIN(*fr); + printf("Time_Bin: %d\n", r0); + fr++; + sz_rd++; + si = 0; + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_HISTO_BIN_IX) { + r0 = GET_HISTO_BIN(*fr); + fr++; + sz_rd++; + printf("Bin %3d Val %5d\n", r0, *fr); + fr++; + sz_rd++; + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_PEDTHR_LIST) { + r0 = GET_PEDTHR_LIST_FEM(*fr); + r1 = GET_PEDTHR_LIST_ASIC(*fr); + r2 = GET_PEDTHR_LIST_MODE(*fr); + r3 = GET_PEDTHR_LIST_TYPE(*fr); + fr++; + sz_rd++; + + if (r3 == 0) { // pedestal entry + printf("# Pedestal List for FEM %02d ASIC %01d\n", r0, r1); + } else { + printf("# Threshold List for FEM %02d ASIC %01d\n", r0, r1); + } + printf("fem %02d\n", r0); + if (r2 == 0) { // AGET + r2 = 71; + } else { + r2 = 78; + } - for (int j=0;j<=r2; j++){ - if(r3==0)printf("ped "); - else printf("thr "); - printf("%1d %2d 0x%04x (%4d)\n", r1, j, *fr, *fr); - fr++; - sz_rd++; - } - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_DFRAME){ - r0 = GET_FRAMING_VERSION(*fr); - r1 = GET_FEMID(*fr); - fr++; - sz_rd++; - printf("--- Start of Data Frame (V.%01d) FEM %02d --\n", r0, r1); - printf("Filled with %d bytes\n", *fr); - fr++; - sz_rd++; - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_MFRAME) { - r0 = GET_FRAMING_VERSION(*fr); - r1 = GET_FEMID(*fr); - printf("--- Start of Moni Frame (V.%01d) FEM %02d --\n", r0, r1); - fr++; - sz_rd++; - printf("Filled with %d bytes\n", *fr); - fr++; - sz_rd++; - } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_CFRAME) { - r0 = GET_FRAMING_VERSION(*fr); - r1 = GET_FEMID(*fr); - fr++; - sz_rd++; - printf("--- Start of Config Frame (V.%01d) FEM %02d --\n", r0, r1); - printf("Error code: %d\n", *((short *) fr)); - fr++; - sz_rd++; - } else if ((*fr & PFX_8_BIT_CONTENT_MASK) == PFX_ASCII_MSG_LEN){ - r0 = GET_ASCII_LEN(*fr); - fr++; - sz_rd++; - printf("ASCII Msg length: %d\n",r0); - for (int j=0;j> 8) ); - fr++; - sz_rd++; - } - if ((*fr) & 0x1){// Skip the null string parity - fr++; - sz_rd++; - } - } else if ((*fr & PFX_4_BIT_CONTENT_MASK) == PFX_START_OF_EVENT) { - r0 = GET_EVENT_TYPE(*fr); - printf("-- Start of Event (Type %01d) --\n", r0); - fr++; - sz_rd++; - uint64_t ts = *fr; - fr++; - sz_rd++; - ts |= ( (*fr) << 16); - fr++; - sz_rd++; - ts |= ( (*fr) << 24); - fr++; - sz_rd++; - printf("Time %" PRId64 "\n", ts); - - uint32_t evC = GetUInt32FromBufferInv(fr, sz_rd);fr+=2; - printf("Event_Count %d\n", evC); - - } else if ((*fr & PFX_4_BIT_CONTENT_MASK) == PFX_END_OF_EVENT){ - uint32_t size_ev = ( GET_EOE_SIZE(*fr)) << 16; - fr++; - sz_rd++; - size_ev |= *fr; - fr++; - sz_rd++; - printf("----- End of Event ----- (size %d bytes)\n", size); - } else if ((*fr & PFX_2_BIT_CONTENT_MASK) == PFX_CH_HIT_CNT_HISTO) { - r0 = GET_CH_HIT_CNT_HISTO_CHIP_IX(*fr); - printf("Channel Hit Count Histogram (ASIC %d)\n", r0); - fr++; - sz_rd++; - //null word - fr++; - sz_rd++; - - fr +=HistoStat_Print (fr, sz_rd, r0); - - } else if ((*fr & PFX_0_BIT_CONTENT_MASK) == PFX_END_OF_FRAME) { - printf("----- End of Frame -----\n"); - fr++; - sz_rd++; - } else if ( *fr == PFX_NULL_CONTENT ) { - printf("null word (2 bytes)\n"); - fr++; - sz_rd++; - } else if ((*fr == PFX_DEADTIME_HSTAT_BINS) || (*fr == PFX_EVPERIOD_HSTAT_BINS)) { - if (*fr == PFX_DEADTIME_HSTAT_BINS)printf("Dead-time Histogram\n"); - else printf("Inter Event Time Histogram\n"); - fr++; - sz_rd++; - //null word - fr++; - sz_rd++; - - fr +=HistoStat_Print (fr, sz_rd, 0); - - } else if (*fr == PFX_PEDESTAL_HSTAT) { - printf("\nPedestal Histogram Statistics\n"); - fr++; - sz_rd++; - - fr+=HistoStat_Print (fr, sz_rd, 0); - - } else if (*fr == PFX_PEDESTAL_H_MD) { - fr++; - sz_rd++; - - uint32_t mean = GetUInt32FromBufferInv(fr, sz_rd);fr+=2; - uint32_t std_dev = GetUInt32FromBufferInv(fr, sz_rd);fr+=2; - printf("Mean/Std_dev : %.2f %.2f\n", (float)mean/100., (float)std_dev/100.); - - fr++; - sz_rd++; - - } else if (*fr == PFX_SHISTO_BINS) { - printf("Threshold Turn-on curve\n"); - fr++; - sz_rd++; - for(int j=0;j<16;j++){ - printf("%d ", *fr); - fr++; - sz_rd++; - } - printf("\n\n"); - } else if (*fr == PFX_CMD_STATISTICS) { - fr++; - sz_rd++; - - uint32_t tmp_i[9]; - for(int j=0;j<9;j++){tmp_i[j] = GetUInt32FromBuffer(fr, sz_rd);fr+=2;} - - printf("Server RX stat: cmd_count=%d daq_req=%d daq_timeout=%d daq_delayed=%d daq_missing=%d cmd_errors=%d\n", tmp_i[0], tmp_i[1], tmp_i[2], tmp_i[3], tmp_i[4], tmp_i[5]); - printf("Server TX stat: cmd_replies=%d daq_replies=%d daq_replies_resent=%d\n", tmp_i[6], tmp_i[7], tmp_i[8]); - } else { // No interpretable data - printf("word(%04d) : 0x%x (%d) unknown data\n", sz_rd, *fr, *fr); - fr++; - sz_rd++; - } + for (int j = 0; j <= r2; j++) { + if (r3 == 0) + printf("ped "); + else + printf("thr "); + printf("%1d %2d 0x%04x (%4d)\n", r1, j, *fr, *fr); + fr++; + sz_rd++; + } + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_DFRAME) { + r0 = GET_FRAMING_VERSION(*fr); + r1 = GET_FEMID(*fr); + fr++; + sz_rd++; + printf("--- Start of Data Frame (V.%01d) FEM %02d --\n", r0, r1); + printf("Filled with %d bytes\n", *fr); + fr++; + sz_rd++; + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_MFRAME) { + r0 = GET_FRAMING_VERSION(*fr); + r1 = GET_FEMID(*fr); + printf("--- Start of Moni Frame (V.%01d) FEM %02d --\n", r0, r1); + fr++; + sz_rd++; + printf("Filled with %d bytes\n", *fr); + fr++; + sz_rd++; + } else if ((*fr & PFX_9_BIT_CONTENT_MASK) == PFX_START_OF_CFRAME) { + r0 = GET_FRAMING_VERSION(*fr); + r1 = GET_FEMID(*fr); + fr++; + sz_rd++; + printf("--- Start of Config Frame (V.%01d) FEM %02d --\n", r0, r1); + printf("Error code: %d\n", *((short*)fr)); + fr++; + sz_rd++; + } else if ((*fr & PFX_8_BIT_CONTENT_MASK) == PFX_ASCII_MSG_LEN) { + r0 = GET_ASCII_LEN(*fr); + fr++; + sz_rd++; + printf("ASCII Msg length: %d\n", r0); + for (int j = 0; j < r0 / 2; j++) { + printf("%c%c", ((*fr) & 0xFF), ((*fr) >> 8)); + fr++; + sz_rd++; + } + if ((*fr) & 0x1) { // Skip the null string parity + fr++; + sz_rd++; + } + } else if ((*fr & PFX_4_BIT_CONTENT_MASK) == PFX_START_OF_EVENT) { + r0 = GET_EVENT_TYPE(*fr); + printf("-- Start of Event (Type %01d) --\n", r0); + fr++; + sz_rd++; + uint64_t ts = *fr; + fr++; + sz_rd++; + ts |= ((*fr) << 16); + fr++; + sz_rd++; + ts |= ((*fr) << 24); + fr++; + sz_rd++; + printf("Time %" PRId64 "\n", ts); + + uint32_t evC = GetUInt32FromBufferInv(fr, sz_rd); + fr += 2; + printf("Event_Count %d\n", evC); + + } else if ((*fr & PFX_4_BIT_CONTENT_MASK) == PFX_END_OF_EVENT) { + uint32_t size_ev = (GET_EOE_SIZE(*fr)) << 16; + fr++; + sz_rd++; + size_ev |= *fr; + fr++; + sz_rd++; + printf("----- End of Event ----- (size %d bytes)\n", size); + } else if ((*fr & PFX_2_BIT_CONTENT_MASK) == PFX_CH_HIT_CNT_HISTO) { + r0 = GET_CH_HIT_CNT_HISTO_CHIP_IX(*fr); + printf("Channel Hit Count Histogram (ASIC %d)\n", r0); + fr++; + sz_rd++; + // null word + fr++; + sz_rd++; + + fr += HistoStat_Print(fr, sz_rd, r0); + + } else if ((*fr & PFX_0_BIT_CONTENT_MASK) == PFX_END_OF_FRAME) { + printf("----- End of Frame -----\n"); + fr++; + sz_rd++; + } else if (*fr == PFX_NULL_CONTENT) { + printf("null word (2 bytes)\n"); + fr++; + sz_rd++; + } else if ((*fr == PFX_DEADTIME_HSTAT_BINS) || (*fr == PFX_EVPERIOD_HSTAT_BINS)) { + if (*fr == PFX_DEADTIME_HSTAT_BINS) + printf("Dead-time Histogram\n"); + else + printf("Inter Event Time Histogram\n"); + fr++; + sz_rd++; + // null word + fr++; + sz_rd++; + + fr += HistoStat_Print(fr, sz_rd, 0); + + } else if (*fr == PFX_PEDESTAL_HSTAT) { + printf("\nPedestal Histogram Statistics\n"); + fr++; + sz_rd++; + + fr += HistoStat_Print(fr, sz_rd, 0); + + } else if (*fr == PFX_PEDESTAL_H_MD) { + fr++; + sz_rd++; + + uint32_t mean = GetUInt32FromBufferInv(fr, sz_rd); + fr += 2; + uint32_t std_dev = GetUInt32FromBufferInv(fr, sz_rd); + fr += 2; + printf("Mean/Std_dev : %.2f %.2f\n", (float)mean / 100., (float)std_dev / 100.); + + fr++; + sz_rd++; + + } else if (*fr == PFX_SHISTO_BINS) { + printf("Threshold Turn-on curve\n"); + fr++; + sz_rd++; + for (int j = 0; j < 16; j++) { + printf("%d ", *fr); + fr++; + sz_rd++; + } + printf("\n\n"); + } else if (*fr == PFX_CMD_STATISTICS) { + fr++; + sz_rd++; + + uint32_t tmp_i[9]; + for (int j = 0; j < 9; j++) { + tmp_i[j] = GetUInt32FromBuffer(fr, sz_rd); + fr += 2; + } - } while (sz_rd < size); + printf("Server RX stat: cmd_count=%d daq_req=%d daq_timeout=%d daq_delayed=%d daq_missing=%d cmd_errors=%d\n", tmp_i[0], tmp_i[1], + tmp_i[2], tmp_i[3], tmp_i[4], tmp_i[5]); + printf("Server TX stat: cmd_replies=%d daq_replies=%d daq_replies_resent=%d\n", tmp_i[6], tmp_i[7], tmp_i[8]); + } else { // No interpretable data + printf("word(%04d) : 0x%x (%d) unknown data\n", sz_rd, *fr, *fr); + fr++; + sz_rd++; + } - if(sz_rd > size)printf("Format error: read %d words but packet size is %d\n", sz_rd, size); + } while (sz_rd < size); + if (sz_rd > size) printf("Format error: read %d words but packet size is %d\n", sz_rd, size); } -int FEMINOSPacket::HistoStat_Print (uint16_t *fr, int &sz_rd, const uint16_t &hitCount) { - - int length=sz_rd; - - printf("Min Bin : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Max Bin : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Bin Width : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Bin Count : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Min Value : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Max Value : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; - printf("Mean : %.2f\n", ((float) GetUInt32FromBuffer(fr, sz_rd)) / 100.0);fr+=2; - printf("Std Dev : %.2f\n", ((float) GetUInt32FromBuffer(fr, sz_rd)) / 100.0);fr+=2; - printf("Entries : %d\n", GetUInt32FromBuffer(fr, sz_rd));fr+=2; +int FEMINOSPacket::HistoStat_Print(uint16_t* fr, int& sz_rd, const uint16_t& hitCount) { + int length = sz_rd; + + printf("Min Bin : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Max Bin : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Bin Width : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Bin Count : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Min Value : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Max Value : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; + printf("Mean : %.2f\n", ((float)GetUInt32FromBuffer(fr, sz_rd)) / 100.0); + fr += 2; + printf("Std Dev : %.2f\n", ((float)GetUInt32FromBuffer(fr, sz_rd)) / 100.0); + fr += 2; + printf("Entries : %d\n", GetUInt32FromBuffer(fr, sz_rd)); + fr += 2; // Get all bins - for (int j=0; j &buffer, TRestRawSignalEvent* sEvent, uint64_t &tS, uint32_t &ev_count){ - - bool endOfEvent = false; - int physChannel; - //std::cout<<__PRETTY_FUNCTION__<<" "< sData(512,0); - while( (buffer.front() & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE || - (buffer.front() & PFX_9_BIT_CONTENT_MASK ) == PFX_TIME_BIN_IX){ - - if ((buffer.front() & PFX_9_BIT_CONTENT_MASK) == PFX_TIME_BIN_IX) { - timeBin = GET_TIME_BIN(buffer.front()); - } else if ((buffer.front() & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE) { - if(timeBin<512)sData[timeBin] = std::move(GET_ADC_DATA(buffer.front())); - timeBin++; - //std::cout<<"TimeBin "<& buffer, TRestRawSignalEvent* sEvent, uint64_t& tS, uint32_t& ev_count) { + bool endOfEvent = false; + int physChannel; + // std::cout<<__PRETTY_FUNCTION__<<" "< sData(512, 0); + while ((buffer.front() & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE || (buffer.front() & PFX_9_BIT_CONTENT_MASK) == PFX_TIME_BIN_IX) { + if ((buffer.front() & PFX_9_BIT_CONTENT_MASK) == PFX_TIME_BIN_IX) { + timeBin = GET_TIME_BIN(buffer.front()); + } else if ((buffer.front() & PFX_12_BIT_CONTENT_MASK) == PFX_ADC_SAMPLE) { + if (timeBin < 512) sData[timeBin] = std::move(GET_ADC_DATA(buffer.front())); + timeBin++; + // std::cout<<"TimeBin "<AddSignal(rawSignal); - - } else if ( (buffer.front() & PFX_4_BIT_CONTENT_MASK) == PFX_END_OF_EVENT ){ - endOfEvent=true; - //std::cout<<"END OF EVENT "; - buffer.pop_front(); - //std::cout<<" event size "<AddSignal(rawSignal); + + } else if ((buffer.front() & PFX_4_BIT_CONTENT_MASK) == PFX_END_OF_EVENT) { + endOfEvent = true; + // std::cout<<"END OF EVENT "; + buffer.pop_front(); + // std::cout<<" event size "< +#include #include -#include -#include +#include +#include // // Prefix Codes for 14-bit data content // -#define PFX_14_BIT_CONTENT_MASK 0xC000 // Mask to select 2 MSB's of prefix -#define PFX_CARD_CHIP_CHAN_HIT_IX 0xC000 // Index of Card, Chip and Channel Hit -#define PFX_CARD_CHIP_CHAN_HIT_CNT 0x8000 // Nb of Channel hit for given Card and Chip -#define PFX_CARD_CHIP_CHAN_HISTO 0x4000 // Pedestal Histogram for given Card and Chip +#define PFX_14_BIT_CONTENT_MASK 0xC000 // Mask to select 2 MSB's of prefix +#define PFX_CARD_CHIP_CHAN_HIT_IX 0xC000 // Index of Card, Chip and Channel Hit +#define PFX_CARD_CHIP_CHAN_HIT_CNT 0x8000 // Nb of Channel hit for given Card and Chip +#define PFX_CARD_CHIP_CHAN_HISTO 0x4000 // Pedestal Histogram for given Card and Chip -#define PUT_CARD_CHIP_CHAN_HISTO(ca, as, ch) (PFX_CARD_CHIP_CHAN_HISTO | (((ca) & 0x1F) <<9) | (((as) & 0x3) <<7) | (((ch) & 0x7F) <<0)) +#define PUT_CARD_CHIP_CHAN_HISTO(ca, as, ch) (PFX_CARD_CHIP_CHAN_HISTO | (((ca)&0x1F) << 9) | (((as)&0x3) << 7) | (((ch)&0x7F) << 0)) // // Prefix Codes for 12-bit data content // -#define PFX_12_BIT_CONTENT_MASK 0xF000 // Mask to select 4 MSB's of prefix -#define PFX_ADC_SAMPLE 0x3000 // ADC sample -#define PFX_LAT_HISTO_BIN 0x2000 // latency or inter event time histogram bin -#define PFX_CHIP_LAST_CELL_READ 0x1000 // Chip index and last cell read +#define PFX_12_BIT_CONTENT_MASK 0xF000 // Mask to select 4 MSB's of prefix +#define PFX_ADC_SAMPLE 0x3000 // ADC sample +#define PFX_LAT_HISTO_BIN 0x2000 // latency or inter event time histogram bin +#define PFX_CHIP_LAST_CELL_READ 0x1000 // Chip index and last cell read // // Prefix Codes for 9-bit data content // -#define PFX_9_BIT_CONTENT_MASK 0xFE00 // Mask to select 7 MSB's of prefix -#define PFX_TIME_BIN_IX 0x0E00 // Time-bin Index -#define PFX_HISTO_BIN_IX 0x0C00 // Histogram bin Index -#define PFX_PEDTHR_LIST 0x0A00 // List of pedestal or thresholds -#define PFX_START_OF_DFRAME 0x0800 // Start of Data Frame + 5 bit source + 4 bit Version -#define PFX_START_OF_MFRAME 0x0600 // Start of Monitoring Frame + 4 bit Version + 5 bit source -#define PFX_START_OF_CFRAME 0x0400 // Start of Configuration Frame + 4 bit Version + 5 bit source +#define PFX_9_BIT_CONTENT_MASK 0xFE00 // Mask to select 7 MSB's of prefix +#define PFX_TIME_BIN_IX 0x0E00 // Time-bin Index +#define PFX_HISTO_BIN_IX 0x0C00 // Histogram bin Index +#define PFX_PEDTHR_LIST 0x0A00 // List of pedestal or thresholds +#define PFX_START_OF_DFRAME 0x0800 // Start of Data Frame + 5 bit source + 4 bit Version +#define PFX_START_OF_MFRAME 0x0600 // Start of Monitoring Frame + 4 bit Version + 5 bit source +#define PFX_START_OF_CFRAME 0x0400 // Start of Configuration Frame + 4 bit Version + 5 bit source // "0000001" : available for future use -#define PUT_HISTO_BIN_IX(bi) (PFX_HISTO_BIN_IX | ((bi) & 0x1FF)) -#define PUT_PEDTHR_LIST(f, a, m, t) (PFX_PEDTHR_LIST | (((f) & 0x1F)<<4) | (((a) & 0x3)<<2) | (((m) & 0x1)<<1) | (((t) & 0x1)<<0)) +#define PUT_HISTO_BIN_IX(bi) (PFX_HISTO_BIN_IX | ((bi)&0x1FF)) +#define PUT_PEDTHR_LIST(f, a, m, t) (PFX_PEDTHR_LIST | (((f)&0x1F) << 4) | (((a)&0x3) << 2) | (((m)&0x1) << 1) | (((t)&0x1) << 0)) // // Prefix Codes for 8-bit data content // -#define PFX_8_BIT_CONTENT_MASK 0xFF00 // Mask to select 8 MSB's of prefix -#define PFX_ASCII_MSG_LEN 0x0100 // ASCII message length +#define PFX_8_BIT_CONTENT_MASK 0xFF00 // Mask to select 8 MSB's of prefix +#define PFX_ASCII_MSG_LEN 0x0100 // ASCII message length // // Prefix Codes for 4-bit data content // -#define PFX_4_BIT_CONTENT_MASK 0xFFF0 // Mask to select 12 MSB's of prefix -#define PFX_START_OF_EVENT 0x00F0 // Start of Event + 1 bit free + Event Trigger Type -#define PFX_END_OF_EVENT 0x00E0 // End of Event + 4 MSB of size -//#define 0x00D0 // available for future use -//#define 0x00C0 // available for future use -//#define 0x00B0 // available for future use -// "000000001010" : available for future use -// "000000001001" : available for future use -// "000000001000" : available for future use - +#define PFX_4_BIT_CONTENT_MASK 0xFFF0 // Mask to select 12 MSB's of prefix +#define PFX_START_OF_EVENT 0x00F0 // Start of Event + 1 bit free + Event Trigger Type +#define PFX_END_OF_EVENT 0x00E0 // End of Event + 4 MSB of size +// #define 0x00D0 // available for future use +// #define 0x00C0 // available for future use +// #define 0x00B0 // available for future use +// "000000001010" : available for future use +// "000000001001" : available for future use +// "000000001000" : available for future use + // // Prefix Codes for 2-bit data content // -#define PFX_2_BIT_CONTENT_MASK 0xFFFC // Mask to select 14 MSB's of prefix -#define PFX_CH_HIT_CNT_HISTO 0x007C // Channel Hit Count Histogram -// "00000000011110" : available for future use -// "00000000011100" : available for future use -// "00000000011011" : available for future use -// "00000000011010" : available for future use -// "00000000011001" : available for future use -// "00000000011000" : available for future use +#define PFX_2_BIT_CONTENT_MASK 0xFFFC // Mask to select 14 MSB's of prefix +#define PFX_CH_HIT_CNT_HISTO 0x007C // Channel Hit Count Histogram +// "00000000011110" : available for future use +// "00000000011100" : available for future use +// "00000000011011" : available for future use +// "00000000011010" : available for future use +// "00000000011001" : available for future use +// "00000000011000" : available for future use // // Prefix Codes for 1-bit data content // -#define PFX_1_BIT_CONTENT_MASK 0xFFFE // Mask to select 15 MSB's of prefix -// "000000000011111" : available for future use -// "000000000011110" : available for future use -// "000000000011101" : available for future use -// "000000000011100" : available for future use -// "000000000001111" : available for future use -// "000000000001110" : available for future use -// "000000000001101" : available for future use -// "000000000001100" : available for future use -// "000000000001011" : available for future use -// "000000000001010" : available for future use -// "000000000001001" : available for future use -// "000000000001000" : available for future use +#define PFX_1_BIT_CONTENT_MASK 0xFFFE // Mask to select 15 MSB's of prefix +// "000000000011111" : available for future use +// "000000000011110" : available for future use +// "000000000011101" : available for future use +// "000000000011100" : available for future use +// "000000000001111" : available for future use +// "000000000001110" : available for future use +// "000000000001101" : available for future use +// "000000000001100" : available for future use +// "000000000001011" : available for future use +// "000000000001010" : available for future use +// "000000000001001" : available for future use +// "000000000001000" : available for future use // // Prefix Codes for 0-bit data content // -#define PFX_0_BIT_CONTENT_MASK 0xFFFF // Mask to select 16 MSB's of prefix -#define PFX_END_OF_FRAME 0x000F // End of Frame (any type) -#define PFX_DEADTIME_HSTAT_BINS 0x000E // Deadtime statistics and histogram -#define PFX_PEDESTAL_HSTAT 0x000D // Pedestal histogram statistics -#define PFX_PEDESTAL_H_MD 0x000C // Pedestal histogram Mean and Deviation -#define PFX_SHISTO_BINS 0x000B // Hit S-curve histogram -#define PFX_CMD_STATISTICS 0x000A // Command server statistics -#define PFX_START_OF_BUILT_EVENT 0x0009 // Start of built event -#define PFX_END_OF_BUILT_EVENT 0x0008 // End of built event -#define PFX_EVPERIOD_HSTAT_BINS 0x0007 // Inter Event Time statistics and histogram -#define PFX_SOBE_SIZE 0x0006 // Start of built event + Size +#define PFX_0_BIT_CONTENT_MASK 0xFFFF // Mask to select 16 MSB's of prefix +#define PFX_END_OF_FRAME 0x000F // End of Frame (any type) +#define PFX_DEADTIME_HSTAT_BINS 0x000E // Deadtime statistics and histogram +#define PFX_PEDESTAL_HSTAT 0x000D // Pedestal histogram statistics +#define PFX_PEDESTAL_H_MD 0x000C // Pedestal histogram Mean and Deviation +#define PFX_SHISTO_BINS 0x000B // Hit S-curve histogram +#define PFX_CMD_STATISTICS 0x000A // Command server statistics +#define PFX_START_OF_BUILT_EVENT 0x0009 // Start of built event +#define PFX_END_OF_BUILT_EVENT 0x0008 // End of built event +#define PFX_EVPERIOD_HSTAT_BINS 0x0007 // Inter Event Time statistics and histogram +#define PFX_SOBE_SIZE 0x0006 // Start of built event + Size // "0000000000000101" : available for future use // "0000000000000100" : available for future use // "0000000000000011" : available for future use // "0000000000000010" : available for future use // "0000000000000001" : available for future use -#define PFX_NULL_CONTENT 0x0000 // Null content +#define PFX_NULL_CONTENT 0x0000 // Null content // // Macros to extract 14-bit data content // -#define GET_CARD_IX(w) (((w) & 0x3E00) >> 9) -#define GET_CHIP_IX(w) (((w) & 0x0180) >> 7) -#define GET_CHAN_IX(w) (((w) & 0x007F) >> 0) +#define GET_CARD_IX(w) (((w)&0x3E00) >> 9) +#define GET_CHIP_IX(w) (((w)&0x0180) >> 7) +#define GET_CHAN_IX(w) (((w)&0x007F) >> 0) // // Macros to extract 12-bit data content // -#define GET_ADC_DATA(w) (((w) & 0x0FFF) >> 0) -#define GET_LAT_HISTO_BIN(w) (((w) & 0x0FFF) >> 0) -#define PUT_LAT_HISTO_BIN(w) (PFX_LAT_HISTO_BIN | (((w) & 0x0FFF) >> 0)) -#define GET_LST_READ_CELL(w) (((w) & 0x03FF) >> 0) -#define GET_LST_READ_CELL_CHIP_IX(w) (((w) & 0x0C00) >> 10) +#define GET_ADC_DATA(w) (((w)&0x0FFF) >> 0) +#define GET_LAT_HISTO_BIN(w) (((w)&0x0FFF) >> 0) +#define PUT_LAT_HISTO_BIN(w) (PFX_LAT_HISTO_BIN | (((w)&0x0FFF) >> 0)) +#define GET_LST_READ_CELL(w) (((w)&0x03FF) >> 0) +#define GET_LST_READ_CELL_CHIP_IX(w) (((w)&0x0C00) >> 10) // // Macros to extract 9-bit data content // -#define GET_TIME_BIN(w) (((w) & 0x01FF) >> 0) -#define GET_HISTO_BIN(w) (((w) & 0x01FF) >> 0) -#define GET_PEDTHR_LIST_FEM(w) (((w) & 0x01F0) >> 4) -#define GET_PEDTHR_LIST_ASIC(w) (((w) & 0x000C) >> 2) -#define GET_PEDTHR_LIST_MODE(w) (((w) & 0x0002) >> 1) -#define GET_PEDTHR_LIST_TYPE(w) (((w) & 0x0001) >> 0) -#define PUT_FVERSION_FEMID(w, fv, id) (((w) & 0xFE00) | (((fv) & 0x0003) << 7) | (((id) & 0x001F) << 0)) -#define GET_FRAMING_VERSION(w) (((w) & 0x0180) >> 7) -#define GET_FEMID(w) (((w) & 0x001F) >> 0) +#define GET_TIME_BIN(w) (((w)&0x01FF) >> 0) +#define GET_HISTO_BIN(w) (((w)&0x01FF) >> 0) +#define GET_PEDTHR_LIST_FEM(w) (((w)&0x01F0) >> 4) +#define GET_PEDTHR_LIST_ASIC(w) (((w)&0x000C) >> 2) +#define GET_PEDTHR_LIST_MODE(w) (((w)&0x0002) >> 1) +#define GET_PEDTHR_LIST_TYPE(w) (((w)&0x0001) >> 0) +#define PUT_FVERSION_FEMID(w, fv, id) (((w)&0xFE00) | (((fv)&0x0003) << 7) | (((id)&0x001F) << 0)) +#define GET_FRAMING_VERSION(w) (((w)&0x0180) >> 7) +#define GET_FEMID(w) (((w)&0x001F) >> 0) // // Macros to act on 8-bit data content // -#define GET_ASCII_LEN(w) (((w) & 0x00FF) >> 0) -#define PUT_ASCII_LEN(w) (PFX_ASCII_MSG_LEN | ((w) & 0x00FF)) +#define GET_ASCII_LEN(w) (((w)&0x00FF) >> 0) +#define PUT_ASCII_LEN(w) (PFX_ASCII_MSG_LEN | ((w)&0x00FF)) // // Macros to act on 4-bit data content // -#define GET_EVENT_TYPE(w) (((w) & 0x0007) >> 0) -#define GET_EOE_SIZE(w) (((w) & 0x000F) >> 0) +#define GET_EVENT_TYPE(w) (((w)&0x0007) >> 0) +#define GET_EOE_SIZE(w) (((w)&0x000F) >> 0) // // Macros to extract 2-bit data content // -#define GET_CH_HIT_CNT_HISTO_CHIP_IX(w) (((w) & 0x0003) >> 0) -#define PUT_CH_HIT_CNT_HISTO_CHIP_IX(w) (PFX_CH_HIT_CNT_HISTO | ((w) & 0x0003)) +#define GET_CH_HIT_CNT_HISTO_CHIP_IX(w) (((w)&0x0003) >> 0) +#define PUT_CH_HIT_CNT_HISTO_CHIP_IX(w) (PFX_CH_HIT_CNT_HISTO | ((w)&0x0003)) #define CURRENT_FRAMING_VERSION 0 -#include "TRestRawSignalEvent.h" +#include #include namespace FEMINOSPacket { - //enum class packetReply { ERROR = -1, RETRY = 0, OK = 1 }; - //enum class packetType { ASCII = 0, BINARY = 1 }; +// enum class packetReply { ERROR = -1, RETRY = 0, OK = 1 }; +// enum class packetType { ASCII = 0, BINARY = 1 }; - void DataPacket_Print(uint16_t *fr, const uint16_t &size); - int HistoStat_Print (uint16_t *fr, int &sz_rd, const uint16_t &hitCount); - uint32_t GetUInt32FromBuffer(uint16_t *fr, int & sz_rd); - uint32_t GetUInt32FromBufferInv(uint16_t *fr, int & sz_rd); - bool GetNextEvent(std::deque &buffer, TRestRawSignalEvent* sEvent, uint64_t &tS, uint32_t &ev_count); - bool isDataFrame(uint16_t *fr); +void DataPacket_Print(uint16_t* fr, const uint16_t& size); +int HistoStat_Print(uint16_t* fr, int& sz_rd, const uint16_t& hitCount); +uint32_t GetUInt32FromBuffer(uint16_t* fr, int& sz_rd); +uint32_t GetUInt32FromBufferInv(uint16_t* fr, int& sz_rd); +bool GetNextEvent(std::deque& buffer, TRestRawSignalEvent* sEvent, uint64_t& tS, uint32_t& ev_count); +bool isDataFrame(uint16_t* fr); -} +} // namespace FEMINOSPacket #endif diff --git a/daq/TRESTDAQ.cxx b/daq/TRESTDAQ.cxx index 6324c94..6b5f8d0 100644 --- a/daq/TRESTDAQ.cxx +++ b/daq/TRESTDAQ.cxx @@ -19,33 +19,31 @@ TRESTDAQ::TRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM) { daqMetadata = dM; verboseLevel = daqMetadata->GetVerboseLevel(); fSignalEvent = new TRestRawSignalEvent(); - if(restRun) - restRun->AddEventBranch(fSignalEvent); + if (restRun) restRun->AddEventBranch(fSignalEvent); } TRESTDAQ::~TRESTDAQ() { // Cleanup if any - event_cnt=0; + event_cnt = 0; } Double_t TRESTDAQ::getCurrentTime() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000.0; } -void TRESTDAQ::FillTree(TRestRun *rR, TRestRawSignalEvent* sEvent) { - - const double evTime = sEvent->GetTime(); - - if(rR){ - rR->GetAnalysisTree()->SetEventInfo(sEvent); - rR->GetEventTree()->Fill(); - rR->GetAnalysisTree()->Fill(); - // AutoSave is needed to read and write at the same time - if (event_cnt % 100 == 0 || (evTime - lastEvTime) > 10 ) { - rR->GetEventTree()->AutoSave("SaveSelf"); +void TRESTDAQ::FillTree(TRestRun* rR, TRestRawSignalEvent* sEvent) { + const double evTime = sEvent->GetTime(); + + if (rR) { + rR->GetAnalysisTree()->SetEventInfo(sEvent); + rR->GetEventTree()->Fill(); + rR->GetAnalysisTree()->Fill(); + // AutoSave is needed to read and write at the same time + if (event_cnt % 100 == 0 || (evTime - lastEvTime) > 10) { + rR->GetEventTree()->AutoSave("SaveSelf"); + } } - } - event_cnt++; - - lastEvTime = evTime; + event_cnt++; + + lastEvTime = evTime; } diff --git a/daq/TRESTDAQ.h b/daq/TRESTDAQ.h index c7038ce..eba41df 100644 --- a/daq/TRESTDAQ.h +++ b/daq/TRESTDAQ.h @@ -12,13 +12,14 @@ To implement generic methods here #ifndef __TREST_DAQ__ #define __TREST_DAQ__ +#include +#include +#include + #include #include #include "TRESTDAQException.h" -#include "TRestRawDAQMetadata.h" -#include "TRestRawSignalEvent.h" -#include "TRestRun.h" class TRESTDAQ { public: diff --git a/daq/TRESTDAQDCC.cxx b/daq/TRESTDAQDCC.cxx index 82091ca..a47577b 100644 --- a/daq/TRESTDAQDCC.cxx +++ b/daq/TRESTDAQDCC.cxx @@ -12,23 +12,22 @@ Author: JuanAn Garcia 18/05/2021 TRESTDAQDCC::TRESTDAQDCC(TRestRun* rR, TRestRawDAQMetadata* dM) : TRESTDAQ(rR, dM) { initialize(); } void TRESTDAQDCC::initialize() { - dcc_socket.Open(GetDAQMetadata()->GetBaseIp(),GetDAQMetadata()->GetLocalIp(), REMOTE_DST_PORT); + dcc_socket.Open(GetDAQMetadata()->GetBaseIp(), GetDAQMetadata()->GetLocalIp(), REMOTE_DST_PORT); - for(auto fec : GetDAQMetadata()->GetFECs()){ - FECMask |= (1 << fec.id); - if(nFECs==0)startFEC = fec.id; + for (auto fec : GetDAQMetadata()->GetFECs()) { + FECMask |= (1 << fec.id); + if (nFECs == 0) startFEC = fec.id; endFEC = fec.id; - nFECs++; + nFECs++; } - } void TRESTDAQDCC::configure() { std::cout << "Configuring readout" << std::endl; char cmd[200]; - if( SendCommand("fem 0") == DCCPacket::packetReply::ERROR)//Check first command, thow exception if DCC doesn't reply - throw (TRESTDAQException("I didn't get reply from the DCC, please check the network")); + if (SendCommand("fem 0") == DCCPacket::packetReply::ERROR) // Check first command, thow exception if DCC doesn't reply + throw(TRESTDAQException("I didn't get reply from the DCC, please check the network")); // SendCommand("triglat 3 2000");//Trigger latency SendCommand("pokes 0x8 0x0000"); // Disable pulser @@ -37,23 +36,23 @@ void TRESTDAQDCC::configure() { SendCommand(cmd); SendCommand("pokes 0x16 0x0"); // Set trigger delay SendCommand("pokes 0x1A 0x1ff"); // SCA delay and trigger - if (GetDAQMetadata()->GetAcquisitionType() == "pedestal"){ + if (GetDAQMetadata()->GetAcquisitionType() == "pedestal") { SendCommand("pokes 0x14 0x400"); // Set SCA readback offset - } else { + } else { SendCommand("pokes 0x14 0xc00"); // Set SCA readback offset - } + } int pk = 0xffc0 | FECMask; sprintf(cmd, "pokeb 0x4 0x%X", pk); // Set FEC mask, note that is inverted SendCommand(cmd); // SendCommand("pokeb 0x5 0x0",-1);//Deplecated? // Configure AFTER chip - for(auto fec : GetDAQMetadata()->GetFECs()) { + for (auto fec : GetDAQMetadata()->GetFECs()) { sprintf(cmd, "fec %d", fec.id); SendCommand(cmd); - for (int a = 0; a < 4; a++) { - if(!fec.asic_isActive[a])continue; - unsigned int reg = ( (fec.asic_shappingTime[a] & 0xF) << 3) | ( (fec.asic_gain[a] & 0x3) << 1) ; + for (int a = 0; a < 4; a++) { + if (!fec.asic_isActive[a]) continue; + unsigned int reg = ((fec.asic_shappingTime[a] & 0xF) << 3) | ((fec.asic_gain[a] & 0x3) << 1); sprintf(cmd, "asic %d write 1 0x%X", a, reg); // Gain and shapping time SendCommand(cmd); sprintf(cmd, "asic %d write 2 0xA000", a); // Output buffers @@ -62,7 +61,7 @@ void TRESTDAQDCC::configure() { SendCommand(cmd); sprintf(cmd, "asic %d write 4 0x3f 0xffff 0xffff", a); SendCommand(cmd); - } + } } // SendCommand("isobus 0x0F", -1);//Reset event counter, timestamp set eventType to test } @@ -101,27 +100,28 @@ void TRESTDAQDCC::pedestal() { SendCommand("isobus 0x1C"); // SCA stop waitForTrigger(); SendCommand("fem 0"); - for(auto fec : GetDAQMetadata()->GetFECs()) { + for (auto fec : GetDAQMetadata()->GetFECs()) { for (int a = 0; a < 4; a++) { - if(!fec.asic_isActive[a])continue; - sprintf(cmd, "hped acc %d %d %d:%d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); - SendCommand(cmd); // Get pedestals + if (!fec.asic_isActive[a]) continue; + sprintf(cmd, "hped acc %d %d %d:%d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); + SendCommand(cmd); // Get pedestals } - } + } } SendCommand("fem 0"); - for(auto fec : GetDAQMetadata()->GetFECs()) { - for (int a = 0; a < 4; a++) { - if(!fec.asic_isActive[a])continue; - sprintf(cmd, "hped getsummary %d %d %d:%d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); - SendCommand(cmd, DCCPacket::packetType::BINARY, 1); // Get summary - sprintf(cmd, "hped centermean %d %d %d:%d %d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a], fec.asic_pedCenter[a]); - SendCommand(cmd); // Set mean - sprintf(cmd, "hped setthr %d %d %d:%d %d %.1f", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a], fec.asic_pedCenter[a], fec.asic_pedThr[a]); - SendCommand(cmd); // Set threshold - } - } + for (auto fec : GetDAQMetadata()->GetFECs()) { + for (int a = 0; a < 4; a++) { + if (!fec.asic_isActive[a]) continue; + sprintf(cmd, "hped getsummary %d %d %d:%d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); + SendCommand(cmd, DCCPacket::packetType::BINARY, 1); // Get summary + sprintf(cmd, "hped centermean %d %d %d:%d %d", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a], fec.asic_pedCenter[a]); + SendCommand(cmd); // Set mean + sprintf(cmd, "hped setthr %d %d %d:%d %d %.1f", fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a], fec.asic_pedCenter[a], + fec.asic_pedThr[a]); + SendCommand(cmd); // Set threshold + } + } } void TRESTDAQDCC::dataTaking() { @@ -136,22 +136,22 @@ void TRESTDAQDCC::dataTaking() { while (!abrt && (GetDAQMetadata()->GetNEvents() == 0 || event_cnt < GetDAQMetadata()->GetNEvents())) { SendCommand("fem 0"); - SendCommand("isobus 0x6C");// SCA start + SendCommand("isobus 0x6C"); // SCA start if (GetDAQMetadata()->GetTriggerType() == "internal") SendCommand("isobus 0x1C"); // SCA stop case of internal trigger GetSignalEvent()->Initialize(); GetSignalEvent()->SetID(event_cnt); waitForTrigger(); // Perform data acquisition phase, compress, accept size GetSignalEvent()->SetTime(getCurrentTime()); - for(auto fec : GetDAQMetadata()->GetFECs()) { + for (auto fec : GetDAQMetadata()->GetFECs()) { for (int a = 0; a < 4; a++) { - if(!fec.asic_isActive[a])continue; - sprintf(cmd, "areq %d %d %d %d %d", GetDAQMetadata()->GetCompressMode(), fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); - SendCommand(cmd, DCCPacket::packetType::BINARY); + if (!fec.asic_isActive[a]) continue; + sprintf(cmd, "areq %d %d %d %d %d", GetDAQMetadata()->GetCompressMode(), fec.id, a, fec.asic_channelStart[a], fec.asic_channelEnd[a]); + SendCommand(cmd, DCCPacket::packetType::BINARY); } - } + } - FillTree(GetRestRun(),GetSignalEvent()); + FillTree(GetRestRun(), GetSignalEvent()); } } @@ -165,8 +165,8 @@ void TRESTDAQDCC::saveEvent(unsigned char* buf, int size) { if (size <= 0) return; DCCPacket::DataPacket* dp = (DCCPacket::DataPacket*)buf; - //Check if packet has ADC data - if( GET_TYPE(ntohs(dp->hdr) ) != RESP_TYPE_ADC_DATA )return; + // Check if packet has ADC data + if (GET_TYPE(ntohs(dp->hdr)) != RESP_TYPE_ADC_DATA) return; const unsigned int scnt = ntohs(dp->scnt); if ((scnt <= 8) && (ntohs(dp->samp[0]) == 0) && (ntohs(dp->samp[1]) == 0)) return; // empty data @@ -182,24 +182,24 @@ void TRESTDAQDCC::saveEvent(unsigned char* buf, int size) { if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) std::cout << "FEC " << fec << " asic " << asic << " channel " << channel << " physChann " << physChannel << "\n"; - //bool compress = GET_RB_COMPRESS(ntohs(dp->args) ); - std::vector sData(512, 0); - Short_t *sDataPtr = sData.data(); + // bool compress = GET_RB_COMPRESS(ntohs(dp->args) ); + std::vector sData(512, 0); + Short_t* sDataPtr = sData.data(); - unsigned short timeBin = 0; + unsigned short timeBin = 0; - for (int i = 0; i < scnt && i<511; i++) { + for (int i = 0; i < scnt && i < 511; i++) { Short_t data = ntohs(dp->samp[i]); - if (((data & 0xFE00) >> 9) == 8) { - timeBin = GET_CELL_INDEX(data); - } else if ((((data & 0xF000) >> 12) == 0)) {//Check fastest method - if (timeBin < 512) sDataPtr[timeBin] = std::move(data); - //if (timeBin < 512) sDataPtr[timeBin] = data; - //if (timeBin < 512)memcpy(&sData[timeBin],&data,sizeof(Short_t)); - //if (timeBin < 512)std::copy(&sData[timeBin],&sData[timeBin], &data); - timeBin++; - } - } + if (((data & 0xFE00) >> 9) == 8) { + timeBin = GET_CELL_INDEX(data); + } else if ((((data & 0xF000) >> 12) == 0)) { // Check fastest method + if (timeBin < 512) sDataPtr[timeBin] = std::move(data); + // if (timeBin < 512) sDataPtr[timeBin] = data; + // if (timeBin < 512)memcpy(&sData[timeBin],&data,sizeof(Short_t)); + // if (timeBin < 512)std::copy(&sData[timeBin],&sData[timeBin], &data); + timeBin++; + } + } TRestRawSignal rawSignal(physChannel, sData); GetSignalEvent()->AddSignal(rawSignal); @@ -207,12 +207,12 @@ void TRESTDAQDCC::saveEvent(unsigned char* buf, int size) { DCCPacket::packetReply TRESTDAQDCC::SendCommand(const char* cmd, DCCPacket::packetType pckType, size_t nPackets) { if (sendto(dcc_socket.client, cmd, strlen(cmd), 0, (struct sockaddr*)&(dcc_socket.target), sizeof(struct sockaddr)) == -1) { - std::string error ="sendto failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); - //return DCCPacket::packetReply::ERROR; + std::string error = "sendto failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); + // return DCCPacket::packetReply::ERROR; } - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug)std::cout<<"Command sent "<= TRestStringOutput::REST_Verbose_Level::REST_Debug) std::cout << "Command sent " << cmd << std::endl; // wait for incoming messages bool done = false; @@ -234,18 +234,19 @@ DCCPacket::packetReply TRESTDAQDCC::SendCommand(const char* cmd, DCCPacket::pack if (errno == EWOULDBLOCK || errno == EAGAIN) { if (cnt % 1000 == 0) { duration = std::chrono::duration_cast>(std::chrono::steady_clock::now() - startTime); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Extreme) fprintf(stderr, "socket() failed: %s\n", strerror(errno)); + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Extreme) + fprintf(stderr, "socket() failed: %s\n", strerror(errno)); } } else { - std::string error ="recvfrom failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + std::string error = "recvfrom failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } } cnt++; } while (length < 0 && duration.count() < 10 && !abrt); - if(abrt){ - std::cerr << "Run aborted" << std::endl; + if (abrt) { + std::cerr << "Run aborted" << std::endl; return DCCPacket::packetReply::ERROR; } @@ -284,11 +285,11 @@ DCCPacket::packetReply TRESTDAQDCC::SendCommand(const char* cmd, DCCPacket::pack DCCPacket::DataPacket* data_pkt = (DCCPacket::DataPacket*)buf_ual; - if(nPackets==0)saveEvent(buf_ual, length); + if (nPackets == 0) saveEvent(buf_ual, length); // Check End Of Event if (GET_FRAME_TY_V2(ntohs(data_pkt->dcchdr)) & FRAME_FLAG_EOEV || GET_FRAME_TY_V2(ntohs(data_pkt->dcchdr)) & FRAME_FLAG_EORQ || - (nPackets >0 && pckCnt >= nPackets) ) { + (nPackets > 0 && pckCnt >= nPackets)) { done = true; } @@ -304,7 +305,6 @@ DCCPacket::packetReply TRESTDAQDCC::SendCommand(const char* cmd, DCCPacket::pack void TRESTDAQDCC::waitForTrigger() { // Wait till trigger is acquired DCCPacket::packetReply reply; do { - reply = SendCommand("wait 1000000"); // Wait for the event to be acquired + reply = SendCommand("wait 1000000"); // Wait for the event to be acquired } while (reply == DCCPacket::packetReply::RETRY && !abrt); // Infinite loop till aborted or wait succeed } - diff --git a/daq/TRESTDAQDCC.h b/daq/TRESTDAQDCC.h index 4ec9044..ef5f649 100644 --- a/daq/TRESTDAQDCC.h +++ b/daq/TRESTDAQDCC.h @@ -12,8 +12,8 @@ Based on mclient program from Denis Calvet #ifndef __TREST_DAQ_DCC__ #define __TREST_DAQ_DCC__ -#include "TRESTDAQ.h" #include "DCCPacket.h" +#include "TRESTDAQ.h" #include "TRESTDAQSocket.h" class TRESTDAQDCC : public TRESTDAQ { @@ -33,13 +33,13 @@ class TRESTDAQDCC : public TRESTDAQ { void waitForTrigger(); void saveEvent(unsigned char* buf, int size); - uint16_t FECMask=0; + uint16_t FECMask = 0; int startFEC; int endFEC; - int chStart=3; - int chEnd=78; - int nFECs=0; + int chStart = 3; + int chEnd = 78; + int nFECs = 0; // Socket TRESTDAQSocket dcc_socket; diff --git a/daq/TRESTDAQDummy.cxx b/daq/TRESTDAQDummy.cxx index 621d751..26f1a7d 100644 --- a/daq/TRESTDAQDummy.cxx +++ b/daq/TRESTDAQDummy.cxx @@ -43,7 +43,7 @@ void TRESTDAQDummy::startDAQ() { physChannel++; } - FillTree(GetRestRun(),GetSignalEvent()); + FillTree(GetRestRun(), GetSignalEvent()); } } diff --git a/daq/TRESTDAQException.h b/daq/TRESTDAQException.h index 95a848f..0f9b1a3 100644 --- a/daq/TRESTDAQException.h +++ b/daq/TRESTDAQException.h @@ -2,22 +2,18 @@ #ifndef __TREST_DAQ_EXCEPTION__ #define __TREST_DAQ_EXCEPTION__ -#include - +#include class TRESTDAQException : public std::exception { - public: - TRESTDAQException(const std::string& msg) : m_msg(msg){ - } + public: + TRESTDAQException(const std::string& msg) : m_msg(msg) {} + + ~TRESTDAQException() {} - ~TRESTDAQException(){ } + virtual const char* what() const throw() { return m_msg.c_str(); } - virtual const char* what() const throw () { - return m_msg.c_str(); - } - private: - const std::string m_msg; + private: + const std::string m_msg; }; #endif - diff --git a/daq/TRESTDAQFEMINOS.cxx b/daq/TRESTDAQFEMINOS.cxx index 6cede92..00e69dd 100644 --- a/daq/TRESTDAQFEMINOS.cxx +++ b/daq/TRESTDAQFEMINOS.cxx @@ -8,139 +8,137 @@ Author: JuanAn Garcia 18/08/2021 *********************************************************************************/ #include "TRESTDAQFEMINOS.h" -#include "FEMINOSPacket.h" +#include "FEMINOSPacket.h" std::atomic TRESTDAQFEMINOS::stopReceiver(false); TRESTDAQFEMINOS::TRESTDAQFEMINOS(TRestRun* rR, TRestRawDAQMetadata* dM) : TRESTDAQ(rR, dM) { initialize(); } void TRESTDAQFEMINOS::initialize() { + // FEMArray.reserve(GetDAQMetadata()->GetFECs().size() );//Reserve space for all the feminos inside the FEC - //FEMArray.reserve(GetDAQMetadata()->GetFECs().size() );//Reserve space for all the feminos inside the FEC - - int *baseIp = GetDAQMetadata()->GetBaseIp(); + int* baseIp = GetDAQMetadata()->GetBaseIp(); - for(auto fec : GetDAQMetadata()->GetFECs()){ + for (auto fec : GetDAQMetadata()->GetFECs()) { FEMProxy FEM; FEM.Open(fec.ip, GetDAQMetadata()->GetLocalIp(), REMOTE_DST_PORT); FEM.fecMetadata = fec; FEMArray.emplace_back(std::move(FEM)); } - //Start receive and event builder threads - receiveThread = std::thread( TRESTDAQFEMINOS::ReceiveThread, &FEMArray); - eventBuilderThread = std::thread( TRESTDAQFEMINOS::EventBuilderThread, &FEMArray, GetRestRun(),GetSignalEvent()); + // Start receive and event builder threads + receiveThread = std::thread(TRESTDAQFEMINOS::ReceiveThread, &FEMArray); + eventBuilderThread = std::thread(TRESTDAQFEMINOS::EventBuilderThread, &FEMArray, GetRestRun(), GetSignalEvent()); } -void TRESTDAQFEMINOS::startUp(){ - std::cout << "Starting up readout" << std::endl; - //FEC Power-down - BroadcastCommand("power_inv 0",FEMArray); - BroadcastCommand("fec_enable 0",FEMArray); - //Ring Buffer and DAQ cleanup - //BroadcastCommand("daq 0x000000 F",FEMArray,false); - BroadcastCommand("daq 0xFFFFFF F",FEMArray); - BroadcastCommand("sca enable 0",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(1)); - BroadcastCommand("serve_target 0",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(4)); - BroadcastCommand("rbf getpnd",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(1)); - //Ring Buffer startup - BroadcastCommand("rbf timed 1",FEMArray); - BroadcastCommand("rbf timeval 2",FEMArray); - BroadcastCommand("rbf resume",FEMArray); - //Selection of operating mode - for (auto &FEM : FEMArray){ - char cmd[200]; - sprintf(cmd, "mode %s", FEM.fecMetadata.chipType.Data()); - SendCommand(cmd,FEM); - uint8_t asicMask =0; - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a]){ - asicMask |= (1 << a); - continue; +void TRESTDAQFEMINOS::startUp() { + std::cout << "Starting up readout" << std::endl; + // FEC Power-down + BroadcastCommand("power_inv 0", FEMArray); + BroadcastCommand("fec_enable 0", FEMArray); + // Ring Buffer and DAQ cleanup + // BroadcastCommand("daq 0x000000 F",FEMArray,false); + BroadcastCommand("daq 0xFFFFFF F", FEMArray); + BroadcastCommand("sca enable 0", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(1)); + BroadcastCommand("serve_target 0", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(4)); + BroadcastCommand("rbf getpnd", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(1)); + // Ring Buffer startup + BroadcastCommand("rbf timed 1", FEMArray); + BroadcastCommand("rbf timeval 2", FEMArray); + BroadcastCommand("rbf resume", FEMArray); + // Selection of operating mode + for (auto& FEM : FEMArray) { + char cmd[200]; + sprintf(cmd, "mode %s", FEM.fecMetadata.chipType.Data()); + SendCommand(cmd, FEM); + uint8_t asicMask = 0; + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) { + asicMask |= (1 << a); + continue; } - sprintf(cmd, "polarity %d %d", a, FEM.fecMetadata.asic_polarity[a]); - SendCommand(cmd,FEM); + sprintf(cmd, "polarity %d %d", a, FEM.fecMetadata.asic_polarity[a]); + SendCommand(cmd, FEM); } - //FEC Power-up and ASIC activation - SendCommand("fec_enable 1",FEM); - sprintf(cmd, "asic_mask 0x%X", asicMask); - SendCommand(cmd,FEM); + // FEC Power-up and ASIC activation + SendCommand("fec_enable 1", FEM); + sprintf(cmd, "asic_mask 0x%X", asicMask); + SendCommand(cmd, FEM); } - } void TRESTDAQFEMINOS::configure() { - std::cout << "Configuring readout" << std::endl; - char cmd[200]; - //Feminos settings - //Selection of operating mode - for (auto &FEM : FEMArray){ - sprintf(cmd, "sca wckdiv 0x%X", FEM.fecMetadata.clockDiv); // Clock div - SendCommand(cmd,FEM); + std::cout << "Configuring readout" << std::endl; + char cmd[200]; + // Feminos settings + // Selection of operating mode + for (auto& FEM : FEMArray) { + sprintf(cmd, "sca wckdiv 0x%X", FEM.fecMetadata.clockDiv); // Clock div + SendCommand(cmd, FEM); } - BroadcastCommand("sca cnt 0x200",FEMArray); - BroadcastCommand("sca autostart 1",FEMArray); - BroadcastCommand("rst_len 0",FEMArray); - //AGET settings - for (auto &FEM : FEMArray){ - if(FEM.fecMetadata.chipType != "aget"){ - std::string error = std::string(FEM.fecMetadata.chipType) +" mode not supported in FEMINOS cards"; - throw (TRESTDAQException(error)); - } - - SendCommand("aget * autoreset_bank 0x1",FEM); - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a])continue; - if(FEM.fecMetadata.asic_polarity[a] == 0){ - sprintf(cmd, "aget %d vicm 0x1", a); - SendCommand(cmd,FEM); - sprintf(cmd, "aget %d polarity 0x0", a); - SendCommand(cmd,FEM); + BroadcastCommand("sca cnt 0x200", FEMArray); + BroadcastCommand("sca autostart 1", FEMArray); + BroadcastCommand("rst_len 0", FEMArray); + // AGET settings + for (auto& FEM : FEMArray) { + if (FEM.fecMetadata.chipType != "aget") { + std::string error = std::string(FEM.fecMetadata.chipType) + " mode not supported in FEMINOS cards"; + throw(TRESTDAQException(error)); + } + + SendCommand("aget * autoreset_bank 0x1", FEM); + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) continue; + if (FEM.fecMetadata.asic_polarity[a] == 0) { + sprintf(cmd, "aget %d vicm 0x1", a); + SendCommand(cmd, FEM); + sprintf(cmd, "aget %d polarity 0x0", a); + SendCommand(cmd, FEM); } else { - sprintf(cmd, "aget %d vicm 0x2", a); - SendCommand(cmd,FEM); - sprintf(cmd, "aget %d polarity 0x1", a); - SendCommand(cmd,FEM); + sprintf(cmd, "aget %d vicm 0x2", a); + SendCommand(cmd, FEM); + sprintf(cmd, "aget %d polarity 0x1", a); + SendCommand(cmd, FEM); } } - SendCommand("aget * en_mkr_rst 0x0",FEM); - SendCommand("aget * rst_level 0x1",FEM); - SendCommand("aget * short_read 0x1",FEM); - SendCommand("aget * tst_digout 0x1",FEM); - SendCommand("aget * mode 0x1",FEM); - - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a])continue; - sprintf(cmd, "aget %d gain * 0x%X",a, (FEM.fecMetadata.asic_gain[a] & 0x3) ); //Gain - SendCommand(cmd,FEM); - sprintf(cmd, "aget %d time 0x%X",a, (FEM.fecMetadata.asic_shappingTime[a] & 0xF) ); //Shapping time - SendCommand(cmd,FEM); + SendCommand("aget * en_mkr_rst 0x0", FEM); + SendCommand("aget * rst_level 0x1", FEM); + SendCommand("aget * short_read 0x1", FEM); + SendCommand("aget * tst_digout 0x1", FEM); + SendCommand("aget * mode 0x1", FEM); + + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) continue; + sprintf(cmd, "aget %d gain * 0x%X", a, (FEM.fecMetadata.asic_gain[a] & 0x3)); // Gain + SendCommand(cmd, FEM); + sprintf(cmd, "aget %d time 0x%X", a, (FEM.fecMetadata.asic_shappingTime[a] & 0xF)); // Shapping time + SendCommand(cmd, FEM); } - SendCommand("aget * dac 0x0",FEM); - - //# Channel ena/disable (AGET only) - SendCommand("forceon_all 1",FEM); - SendCommand("forceoff * * 0x1",FEM); - SendCommand("forceon * * 0x0",FEM); - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a])continue; - sprintf(cmd,"forceoff %d * 0x0",a); - SendCommand(cmd,FEM); - sprintf(cmd,"forceon %d * 0x1",a); - SendCommand(cmd,FEM); - for(int c=0;c<78;c++){ - if(FEM.fecMetadata.asic_channelActive[a][c])continue; - sprintf(cmd,"forceoff %d %d 0x1",a); - SendCommand(cmd,FEM); - sprintf(cmd,"forceon %d %d 0x0",a); - SendCommand(cmd,FEM); - } + SendCommand("aget * dac 0x0", FEM); + + // # Channel ena/disable (AGET only) + SendCommand("forceon_all 1", FEM); + SendCommand("forceoff * * 0x1", FEM); + SendCommand("forceon * * 0x0", FEM); + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) continue; + sprintf(cmd, "forceoff %d * 0x0", a); + SendCommand(cmd, FEM); + sprintf(cmd, "forceon %d * 0x1", a); + SendCommand(cmd, FEM); + for (int c = 0; c < 78; c++) { + if (FEM.fecMetadata.asic_channelActive[a][c]) continue; + sprintf(cmd, "forceoff %d %d 0x1", a); + SendCommand(cmd, FEM); + sprintf(cmd, "forceon %d %d 0x0", a); + SendCommand(cmd, FEM); + } } } } @@ -162,303 +160,288 @@ void TRESTDAQFEMINOS::startDAQ() { } void TRESTDAQFEMINOS::pedestal() { - std::cout << "Starting pedestal run" << std::endl; - //Test mode settings - BroadcastCommand("keep_fco 0",FEMArray); - BroadcastCommand("test_zbt 0",FEMArray); - BroadcastCommand("test_enable 0",FEMArray); - BroadcastCommand("test_mode 0",FEMArray); - BroadcastCommand("tdata A 0x40",FEMArray); - //Readout settings - BroadcastCommand("modify_hit_reg 0",FEMArray); - BroadcastCommand("emit_hit_cnt 1",FEMArray); - BroadcastCommand("emit_empty_ch 1",FEMArray); - BroadcastCommand("keep_rst 1",FEMArray); - BroadcastCommand("skip_rst 0",FEMArray); - //Pedestal Thresholds and Zero-suppression - BroadcastCommand("ped * * 0x0",FEMArray); - BroadcastCommand("subtract_ped 0",FEMArray); - BroadcastCommand("zero_suppress 0",FEMArray); - BroadcastCommand("zs_pre_post 0 0",FEMArray); - BroadcastCommand("thr * * 0x0",FEMArray); - //Event generator - BroadcastCommand("event_limit 0x3",FEMArray);//# Event limit: 0x0:infinite; 0x1:1; 0x2:10; 0x3:100; 0x4: 1000; 0x5:10000; 0x6:100000; 0x7:1000000 - BroadcastCommand("trig_rate 1 10",FEMArray);//# Range: 0:0.1Hz-10Hz 1:10Hz-1kHz 2:100Hz-10kHz 3:1kHz-100kHz - BroadcastCommand("trig_enable 0x1",FEMArray); - //Pedestal Histograms - BroadcastCommand("hped offset * * 0",FEMArray); - BroadcastCommand("hped clr * *",FEMArray); - //Data server target: 0:drop data; 1:send to DAQ; 2:feed to pedestal histos; 3:feed to hit channel histos - BroadcastCommand("serve_target 2",FEMArray); - BroadcastCommand("sca enable 1",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(15));// Wait pedestal accumulation completion - BroadcastCommand("sca enable 0",FEMArray); - char cmd[200]; - for (auto &FEM : FEMArray){ - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a])continue; - sprintf(cmd, "hped getsummary %d *", a ); - SendCommand(cmd,FEM); - //Set pedestal equalization - sprintf(cmd, "hped centermean %d * %d", a , FEM.fecMetadata.asic_pedCenter[a] ); - SendCommand(cmd,FEM); - } + std::cout << "Starting pedestal run" << std::endl; + // Test mode settings + BroadcastCommand("keep_fco 0", FEMArray); + BroadcastCommand("test_zbt 0", FEMArray); + BroadcastCommand("test_enable 0", FEMArray); + BroadcastCommand("test_mode 0", FEMArray); + BroadcastCommand("tdata A 0x40", FEMArray); + // Readout settings + BroadcastCommand("modify_hit_reg 0", FEMArray); + BroadcastCommand("emit_hit_cnt 1", FEMArray); + BroadcastCommand("emit_empty_ch 1", FEMArray); + BroadcastCommand("keep_rst 1", FEMArray); + BroadcastCommand("skip_rst 0", FEMArray); + // Pedestal Thresholds and Zero-suppression + BroadcastCommand("ped * * 0x0", FEMArray); + BroadcastCommand("subtract_ped 0", FEMArray); + BroadcastCommand("zero_suppress 0", FEMArray); + BroadcastCommand("zs_pre_post 0 0", FEMArray); + BroadcastCommand("thr * * 0x0", FEMArray); + // Event generator + BroadcastCommand("event_limit 0x3", + FEMArray); // # Event limit: 0x0:infinite; 0x1:1; 0x2:10; 0x3:100; 0x4: 1000; 0x5:10000; 0x6:100000; 0x7:1000000 + BroadcastCommand("trig_rate 1 10", FEMArray); // # Range: 0:0.1Hz-10Hz 1:10Hz-1kHz 2:100Hz-10kHz 3:1kHz-100kHz + BroadcastCommand("trig_enable 0x1", FEMArray); + // Pedestal Histograms + BroadcastCommand("hped offset * * 0", FEMArray); + BroadcastCommand("hped clr * *", FEMArray); + // Data server target: 0:drop data; 1:send to DAQ; 2:feed to pedestal histos; 3:feed to hit channel histos + BroadcastCommand("serve_target 2", FEMArray); + BroadcastCommand("sca enable 1", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(15)); // Wait pedestal accumulation completion + BroadcastCommand("sca enable 0", FEMArray); + char cmd[200]; + for (auto& FEM : FEMArray) { + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) continue; + sprintf(cmd, "hped getsummary %d *", a); + SendCommand(cmd, FEM); + // Set pedestal equalization + sprintf(cmd, "hped centermean %d * %d", a, FEM.fecMetadata.asic_pedCenter[a]); + SendCommand(cmd, FEM); + } } - BroadcastCommand("subtract_ped 1",FEMArray); - BroadcastCommand("hped clr * *",FEMArray); - BroadcastCommand("sca enable 1",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(15));// Wait pedestal accumulation completion - BroadcastCommand("sca enable 0",FEMArray); - for (auto &FEM : FEMArray){ - for(int a=0;a<4;a++){ - if(!FEM.fecMetadata.asic_isActive[a])continue; - sprintf(cmd, "hped getsummary %d *", a ); - SendCommand(cmd,FEM); - //Set threshold - sprintf(cmd, "hped setthr %d * %d %.1f", a , FEM.fecMetadata.asic_pedCenter[a], FEM.fecMetadata.asic_pedThr[a] ); - SendCommand(cmd,FEM); - } + BroadcastCommand("subtract_ped 1", FEMArray); + BroadcastCommand("hped clr * *", FEMArray); + BroadcastCommand("sca enable 1", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(15)); // Wait pedestal accumulation completion + BroadcastCommand("sca enable 0", FEMArray); + for (auto& FEM : FEMArray) { + for (int a = 0; a < 4; a++) { + if (!FEM.fecMetadata.asic_isActive[a]) continue; + sprintf(cmd, "hped getsummary %d *", a); + SendCommand(cmd, FEM); + // Set threshold + sprintf(cmd, "hped setthr %d * %d %.1f", a, FEM.fecMetadata.asic_pedCenter[a], FEM.fecMetadata.asic_pedThr[a]); + SendCommand(cmd, FEM); + } } - //Set Data server target to DAQ - BroadcastCommand("serve_target 1",FEMArray); + // Set Data server target to DAQ + BroadcastCommand("serve_target 1", FEMArray); } void TRESTDAQFEMINOS::dataTaking() { - std::cout << "Starting data taking run" << std::endl; - //BroadcastCommand("daq 0x000000 F",FEMArray,false); - BroadcastCommand("daq 0xFFFFFF F",FEMArray); - BroadcastCommand("sca enable 0",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(1)); - BroadcastCommand("serve_target 0",FEMArray); - std::this_thread::sleep_for(std::chrono::seconds(4)); - //Readout settings - BroadcastCommand("modify_hit_reg 0",FEMArray); - BroadcastCommand("emit_hit_cnt 1",FEMArray); - BroadcastCommand("emit_empty_ch 0",FEMArray); - BroadcastCommand("emit_lst_cell_rd 1",FEMArray); - BroadcastCommand("keep_rst 1",FEMArray); - BroadcastCommand("skip_rst 0",FEMArray); - //AGET settings - if( GetDAQMetadata()->GetChipType() == "aget"){ - BroadcastCommand("aget * mode 0x1",FEMArray);//Mode: 0x0: hit/selected channels 0x1:all channels - BroadcastCommand("aget * tst_digout 1",FEMArray);//?? + std::cout << "Starting data taking run" << std::endl; + // BroadcastCommand("daq 0x000000 F",FEMArray,false); + BroadcastCommand("daq 0xFFFFFF F", FEMArray); + BroadcastCommand("sca enable 0", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(1)); + BroadcastCommand("serve_target 0", FEMArray); + std::this_thread::sleep_for(std::chrono::seconds(4)); + // Readout settings + BroadcastCommand("modify_hit_reg 0", FEMArray); + BroadcastCommand("emit_hit_cnt 1", FEMArray); + BroadcastCommand("emit_empty_ch 0", FEMArray); + BroadcastCommand("emit_lst_cell_rd 1", FEMArray); + BroadcastCommand("keep_rst 1", FEMArray); + BroadcastCommand("skip_rst 0", FEMArray); + // AGET settings + if (GetDAQMetadata()->GetChipType() == "aget") { + BroadcastCommand("aget * mode 0x1", FEMArray); // Mode: 0x0: hit/selected channels 0x1:all channels + BroadcastCommand("aget * tst_digout 1", FEMArray); //?? + } + BroadcastCommand("subtract_ped 1", FEMArray); + if (GetDAQMetadata()->GetCompressMode()) { + BroadcastCommand("zero_suppress 1", FEMArray); + BroadcastCommand("zs_pre_post 8 4", FEMArray); + } else { + BroadcastCommand("zero_suppress 0", FEMArray); + BroadcastCommand("zs_pre_post 0 0", FEMArray); } - BroadcastCommand("subtract_ped 1",FEMArray); - if(GetDAQMetadata()->GetCompressMode()){ - BroadcastCommand("zero_suppress 1",FEMArray); - BroadcastCommand("zs_pre_post 8 4",FEMArray); + // Event generator + BroadcastCommand("clr tstamp", FEMArray); + BroadcastCommand("clr evnct", FEMArray); + BroadcastCommand("event_limit 0x0", FEMArray); // Infinite + if (GetDAQMetadata()->GetTriggerType() == "internal") { + BroadcastCommand("trig_rate 1 50", FEMArray); + BroadcastCommand("trig_enable 0x1", FEMArray); } else { - BroadcastCommand("zero_suppress 0",FEMArray); - BroadcastCommand("zs_pre_post 0 0",FEMArray); + BroadcastCommand("trig_enable 0x8", FEMArray); // tcm??? } - //Event generator - BroadcastCommand("clr tstamp",FEMArray); - BroadcastCommand("clr evnct",FEMArray); - BroadcastCommand("event_limit 0x0",FEMArray);//Infinite - if (GetDAQMetadata()->GetTriggerType() == "internal"){ - BroadcastCommand("trig_rate 1 50",FEMArray); - BroadcastCommand("trig_enable 0x1",FEMArray); - } else { - BroadcastCommand("trig_enable 0x8",FEMArray);//tcm??? - } - BroadcastCommand("serve_target 1",FEMArray);//1: send to DAQ - BroadcastCommand("sca enable 1",FEMArray);//Enable data taking - BroadcastCommand("daq 0xFFFFFE F",FEMArray, false);//DAQ request - //Wait till DAQ completion - while (!abrt && (GetDAQMetadata()->GetNEvents() == 0 || event_cnt < GetDAQMetadata()->GetNEvents())) { - //Do something here? E.g. send packet request + BroadcastCommand("serve_target 1", FEMArray); // 1: send to DAQ + BroadcastCommand("sca enable 1", FEMArray); // Enable data taking + BroadcastCommand("daq 0xFFFFFE F", FEMArray, false); // DAQ request + // Wait till DAQ completion + while (!abrt && (GetDAQMetadata()->GetNEvents() == 0 || event_cnt < GetDAQMetadata()->GetNEvents())) { + // Do something here? E.g. send packet request std::this_thread::sleep_for(std::chrono::milliseconds(200)); - } - BroadcastCommand("sca enable 0",FEMArray); - BroadcastCommand("daq 0xFFFFFF F",FEMArray,false);//Stop DAQ request - std::this_thread::sleep_for(std::chrono::milliseconds(500));//Wait some time till DAQ command is propagated + } + BroadcastCommand("sca enable 0", FEMArray); + BroadcastCommand("daq 0xFFFFFF F", FEMArray, false); // Stop DAQ request + std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Wait some time till DAQ command is propagated } void TRESTDAQFEMINOS::stopDAQ() { - stopReceiver = true; - receiveThread.join(); - eventBuilderThread.join(); + stopReceiver = true; + receiveThread.join(); + eventBuilderThread.join(); - for (auto &FEM : FEMArray) - FEM.Close(); + for (auto& FEM : FEMArray) FEM.Close(); } -void TRESTDAQFEMINOS::BroadcastCommand(const char* cmd, std::vector &FEMA, bool wait){ - - for (auto &FEM : FEMA){ - SendCommand(cmd,FEM,wait); +void TRESTDAQFEMINOS::BroadcastCommand(const char* cmd, std::vector& FEMA, bool wait) { + for (auto& FEM : FEMA) { + SendCommand(cmd, FEM, wait); } - //if (verboseLevel >= REST_Debug)std::cout<<"Command sent "<= REST_Debug)std::cout<<"Command sent "< lock(FEM.mutex_socket); - if (sendto (FEM.client, cmd, strlen(cmd), 0, (struct sockaddr*)&(FEM.target), sizeof(struct sockaddr)) == -1) { - std::string error ="sendto failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); - } - - lock.unlock(); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug)std::cout<<"FEM "< lock(FEM.mutex_socket); + if (sendto(FEM.client, cmd, strlen(cmd), 0, (struct sockaddr*)&(FEM.target), sizeof(struct sockaddr)) == -1) { + std::string error = "sendto failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } -} + lock.unlock(); + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) + std::cout << "FEM " << FEM.fecMetadata.id << " Command sent " << cmd << std::endl; -void TRESTDAQFEMINOS::waitForCmd(FEMProxy &FEM){ + if (wait) { + // lock.lock(); + FEM.cmd_sent++; + // lock.unlock(); + waitForCmd(FEM); + } +} - int timeout = 0; - bool condition; +void TRESTDAQFEMINOS::waitForCmd(FEMProxy& FEM) { + int timeout = 0; + bool condition; do { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - std::unique_lock lock(FEM.mutex_socket); - condition = (FEM.cmd_sent > FEM.cmd_rcv); - lock.unlock(); - timeout++; - } while ( condition && timeout <10); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + std::unique_lock lock(FEM.mutex_socket); + condition = (FEM.cmd_sent > FEM.cmd_rcv); + lock.unlock(); + timeout++; + } while (condition && timeout < 10); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug)std::cout<<"Cmd sent "<= TRestStringOutput::REST_Verbose_Level::REST_Debug) + std::cout << "Cmd sent " << FEM.cmd_sent << " Cmd Received: " << FEM.cmd_rcv << std::endl; - if(timeout>=10)std::cout<<"Cmd timeout "<= 10) std::cout << "Cmd timeout " << std::endl; } -void TRESTDAQFEMINOS::ReceiveThread( std::vector *FEMA ) { - - fd_set readfds, writefds, exceptfds, readfds_work; - struct timeval t_timeout; - t_timeout.tv_sec = 5; - t_timeout.tv_usec = 0; - - // Build the socket descriptor set from which we want to read - FD_ZERO(&readfds); - FD_ZERO(&writefds); - FD_ZERO(&exceptfds); - - - int smax = 0; - for (auto &FEM : *FEMA){ - FD_SET(FEM.client, &readfds); - if (FEM.client > smax) - smax = FEM.client; +void TRESTDAQFEMINOS::ReceiveThread(std::vector* FEMA) { + fd_set readfds, writefds, exceptfds, readfds_work; + struct timeval t_timeout; + t_timeout.tv_sec = 5; + t_timeout.tv_usec = 0; + + // Build the socket descriptor set from which we want to read + FD_ZERO(&readfds); + FD_ZERO(&writefds); + FD_ZERO(&exceptfds); + + int smax = 0; + for (auto& FEM : *FEMA) { + FD_SET(FEM.client, &readfds); + if (FEM.client > smax) smax = FEM.client; } - smax++; + smax++; - while (!stopReceiver){ + while (!stopReceiver) { + // Copy the read fds from what we computed outside of the loop + readfds_work = readfds; - // Copy the read fds from what we computed outside of the loop - readfds_work = readfds; - - int err =0; + int err = 0; // Wait for any of these sockets to be ready - if ((err = select(smax, &readfds_work, &writefds, &exceptfds, &t_timeout)) < 0){ - std::string error ="select failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + if ((err = select(smax, &readfds_work, &writefds, &exceptfds, &t_timeout)) < 0) { + std::string error = "select failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } - if(err == 0 )continue;//Nothing received - - for (auto &FEM : *FEMA){ - - if (FD_ISSET(FEM.client, &readfds_work)){ - std::unique_lock lock(FEM.mutex_socket); - uint16_t buf_rcv[8192/(sizeof(uint16_t))]; - int length = recvfrom(FEM.client, buf_rcv, 8192, 0, (struct sockaddr*)&FEM.remote, &FEM.remote_size); - lock.unlock(); - if (length < 0) { - std::string error ="recvfrom failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); - } - - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug)std::cout<<"Packet received with length "<6){//empty frame? - size_t size = length/sizeof(uint16_t);//Note that length is in bytes while size is uint16_t - - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug)FEMINOSPacket::DataPacket_Print(&buf_rcv[1], size-1); - - - if(!FEMINOSPacket::isDataFrame(&buf_rcv[1])){ - //lock.lock(); - FEM.cmd_rcv++; - //lock.unlock(); - } else { - std::unique_lock lock_mem(FEM.mutex_mem); - //const std::deque frame (&buf_rcv[1], &buf_rcv[size -1]); - FEM.buffer.insert(FEM.buffer.end(), &buf_rcv[3], &buf_rcv[size -1]);//Skip 2 first words - int bufferSize = FEM.buffer.size(); - lock_mem.unlock(); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) - std::cout<<"Packet buffered with size "<<(int)size-1<<" queue size: "< 1024*1024*1024){ - std::string error ="Buffer FULL with size "+std::to_string(bufferSize/sizeof(uint16_t))+" bytes"; - throw (TRESTDAQException(error)); + if (err == 0) continue; // Nothing received + + for (auto& FEM : *FEMA) { + if (FD_ISSET(FEM.client, &readfds_work)) { + std::unique_lock lock(FEM.mutex_socket); + uint16_t buf_rcv[8192 / (sizeof(uint16_t))]; + int length = recvfrom(FEM.client, buf_rcv, 8192, 0, (struct sockaddr*)&FEM.remote, &FEM.remote_size); + lock.unlock(); + if (length < 0) { + std::string error = "recvfrom failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); + } + + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) + std::cout << "Packet received with length " << length << " bytes" << std::endl; + + if (length > 6) { // empty frame? + size_t size = length / sizeof(uint16_t); // Note that length is in bytes while size is uint16_t + + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) FEMINOSPacket::DataPacket_Print(&buf_rcv[1], size - 1); + + if (!FEMINOSPacket::isDataFrame(&buf_rcv[1])) { + // lock.lock(); + FEM.cmd_rcv++; + // lock.unlock(); + } else { + std::unique_lock lock_mem(FEM.mutex_mem); + // const std::deque frame (&buf_rcv[1], &buf_rcv[size -1]); + FEM.buffer.insert(FEM.buffer.end(), &buf_rcv[3], &buf_rcv[size - 1]); // Skip 2 first words + int bufferSize = FEM.buffer.size(); + lock_mem.unlock(); + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) + std::cout << "Packet buffered with size " << (int)size - 1 << " queue size: " << bufferSize << std::endl; + if (bufferSize > 1024 * 1024 * 1024) { + std::string error = "Buffer FULL with size " + std::to_string(bufferSize / sizeof(uint16_t)) + " bytes"; + throw(TRESTDAQException(error)); + } } - - } + } } - } - } } } -void TRESTDAQFEMINOS::EventBuilderThread(std::vector *FEMA, TRestRun *rR, TRestRawSignalEvent* sEvent){ - - sEvent->Initialize(); - - uint32_t ev_count; - uint64_t ts; - - bool newEvent = false; - bool pendingEvent = false; - - while (!stopReceiver ){ - - for (auto &FEM : *FEMA){ - std::unique_lock lock(FEM.mutex_mem); - if(!FEM.buffer.empty()){//Do nothing - if(FEM.pendingEvent){//Wait till we reach end of event for all the FEMINOS - FEM.pendingEvent = !FEMINOSPacket::GetNextEvent( FEM.buffer, sEvent, ts, ev_count); - } else if( !FEM.pendingEvent && !pendingEvent) { - FEM.pendingEvent = !FEMINOSPacket::GetNextEvent( FEM.buffer, sEvent, ts, ev_count); - newEvent=true; - } +void TRESTDAQFEMINOS::EventBuilderThread(std::vector* FEMA, TRestRun* rR, TRestRawSignalEvent* sEvent) { + sEvent->Initialize(); + + uint32_t ev_count; + uint64_t ts; + + bool newEvent = false; + bool pendingEvent = false; + + while (!stopReceiver) { + for (auto& FEM : *FEMA) { + std::unique_lock lock(FEM.mutex_mem); + if (!FEM.buffer.empty()) { // Do nothing + if (FEM.pendingEvent) { // Wait till we reach end of event for all the FEMINOS + FEM.pendingEvent = !FEMINOSPacket::GetNextEvent(FEM.buffer, sEvent, ts, ev_count); + } else if (!FEM.pendingEvent && !pendingEvent) { + FEM.pendingEvent = !FEMINOSPacket::GetNextEvent(FEM.buffer, sEvent, ts, ev_count); + newEvent = true; + } + } + lock.unlock(); } - lock.unlock(); - } - pendingEvent=false; + pendingEvent = false; - for (const auto &FEM : *FEMA){ - //std::unique_lock lock(FEM.mutex_mem); - if(FEM.pendingEvent)pendingEvent=true;//Check if the event is pending - //lock.unlock(); + for (const auto& FEM : *FEMA) { + // std::unique_lock lock(FEM.mutex_mem); + if (FEM.pendingEvent) pendingEvent = true; // Check if the event is pending + // lock.unlock(); } - if(newEvent && !pendingEvent){//Save Event if closed - if(rR){ - sEvent->SetID(ev_count); - sEvent->SetTime( rR->GetStartTimestamp() + (double) ts * 2E-8 ); - FillTree(rR,sEvent); - sEvent->Initialize(); - newEvent =false; - if(event_cnt%100 == 0)std::cout<<"Events "<SetID(ev_count); + sEvent->SetTime(rR->GetStartTimestamp() + (double)ts * 2E-8); + FillTree(rR, sEvent); + sEvent->Initialize(); + newEvent = false; + if (event_cnt % 100 == 0) std::cout << "Events " << event_cnt << std::endl; + } } - } - - } - + } } - - diff --git a/daq/TRESTDAQFEMINOS.h b/daq/TRESTDAQFEMINOS.h index cc52712..1b4302b 100644 --- a/daq/TRESTDAQFEMINOS.h +++ b/daq/TRESTDAQFEMINOS.h @@ -12,34 +12,32 @@ Based on mclient program from Denis Calvet #ifndef __TREST_DAQ_FEMINOS__ #define __TREST_DAQ_FEMINOS__ -#include "TRESTDAQ.h" -#include "TRESTDAQSocket.h" - +#include #include -#include #include -#include +#include + +#include "TRESTDAQ.h" +#include "TRESTDAQSocket.h" class FEMProxy : public TRESTDAQSocket { - - public: - FEMProxy(){ - } - bool pendingEvent=false; + public: + FEMProxy() {} + bool pendingEvent = false; FECMetadata fecMetadata; - //std::atomic_int - int cmd_sent=0; - //std::atomic_int - int cmd_rcv=0; + // std::atomic_int + int cmd_sent = 0; + // std::atomic_int + int cmd_rcv = 0; - std::deque buffer; + std::deque buffer; inline static std::mutex mutex_socket; inline static std::mutex mutex_mem; }; class TRESTDAQFEMINOS : public TRESTDAQ { - public: + public: TRESTDAQFEMINOS(TRestRun* rR, TRestRawDAQMetadata* dM); virtual void configure(); @@ -48,24 +46,23 @@ class TRESTDAQFEMINOS : public TRESTDAQ { virtual void initialize(); virtual void startUp(); - static void ReceiveThread(std::vector *FEMA); - static void ReceiveBuffer(FEMProxy &FEM); - static void EventBuilderThread(std::vector *FEMA, TRestRun *rR, TRestRawSignalEvent* sEvent); - static void waitForCmd(FEMProxy &FEM); + static void ReceiveThread(std::vector* FEMA); + static void ReceiveBuffer(FEMProxy& FEM); + static void EventBuilderThread(std::vector* FEMA, TRestRun* rR, TRestRawSignalEvent* sEvent); + static void waitForCmd(FEMProxy& FEM); static std::atomic stopReceiver; inline static std::mutex mutex; - private: + private: void pedestal(); void dataTaking(); - void BroadcastCommand(const char* cmd, std::vector &FEMA, bool wait=true); - void SendCommand(const char* cmd, FEMProxy &FEM, bool wait=true); + void BroadcastCommand(const char* cmd, std::vector& FEMA, bool wait = true); + void SendCommand(const char* cmd, FEMProxy& FEM, bool wait = true); - std::vector FEMArray;//Vector of FEMINOS + std::vector FEMArray; // Vector of FEMINOS std::thread receiveThread, eventBuilderThread; - }; #endif diff --git a/daq/TRESTDAQManager.h b/daq/TRESTDAQManager.h index c7fed6f..49e8685 100644 --- a/daq/TRESTDAQManager.h +++ b/daq/TRESTDAQManager.h @@ -43,15 +43,15 @@ class TRESTDAQManager { void dataTaking(); void startUp(); - std::unique_ptr GetTRESTDAQ (TRestRun* rR, TRestRawDAQMetadata* dM); + std::unique_ptr GetTRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM); // Shared Memory static void InitializeSharedMemory(sharedMemoryStruct* sM); static void PrintSharedMemory(sharedMemoryStruct* sM); - static bool GetSharedMemory(int& sid, sharedMemoryStruct** sM, int flag =0, bool verbose=true); + static bool GetSharedMemory(int& sid, sharedMemoryStruct** sM, int flag = 0, bool verbose = true); static void DetachSharedMemory(sharedMemoryStruct** sM); - static int GetFileSize(const std::string &filename); + static int GetFileSize(const std::string& filename); // Control commands static void StopRun(); diff --git a/daq/TRESTDAQSocket.cxx b/daq/TRESTDAQSocket.cxx index 5c336a2..2239521 100644 --- a/daq/TRESTDAQSocket.cxx +++ b/daq/TRESTDAQSocket.cxx @@ -1,48 +1,47 @@ #include -void TRESTDAQSocket::Open(int* rem_ip_base, int* loc_ip,int rpt) { - +void TRESTDAQSocket::Open(int* rem_ip_base, int* loc_ip, int rpt) { // Initialize socket - if ( (client = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP) ) == -1) { - std::string error ="Socket open failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + if ((client = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { + std::string error = "Socket open failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } // Set socket in non-blocking mode int nb = 1; if (ioctl(client, FIONBIO, &nb) != 0) { - std::string error ="ioctl socket failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + std::string error = "ioctl socket failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } socklen_t optlen = sizeof(int); int rcvsz_req = 200 * 1024; // Set receive socket size if (setsockopt(client, SOL_SOCKET, SO_RCVBUF, &rcvsz_req, optlen) != 0) { - std::string error ="setsockopt failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + std::string error = "setsockopt failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } int rcvsz_done; // Get receive socket size if (getsockopt(client, SOL_SOCKET, SO_RCVBUF, &rcvsz_done, &optlen) != 0) { - std::string error ="getsockopt failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + std::string error = "getsockopt failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } // Bind the socket to the local IP address struct sockaddr_in src; src.sin_family = PF_INET; // if ( (*(loc_ip+0) == 0) && (*(loc_ip+1) == 0) &&(*(loc_ip+2) == 0) &&(*(loc_ip+3) == 0) ){ - src.sin_addr.s_addr = htonl(INADDR_ANY); - //} else { - // src.sin_addr.s_addr = htonl(((*(loc_ip+0)&0xFF)<<24) | ((*(loc_ip+1)&0xFF)<<16) | ((*(loc_ip+2)&0xFF)<<8) | ((*(loc_ip+3)&0xFF)<<0)); + src.sin_addr.s_addr = htonl(INADDR_ANY); + //} else { + // src.sin_addr.s_addr = htonl(((*(loc_ip+0)&0xFF)<<24) | ((*(loc_ip+1)&0xFF)<<16) | ((*(loc_ip+2)&0xFF)<<8) | ((*(loc_ip+3)&0xFF)<<0)); // } - src.sin_port = 0; - if (bind(client, (struct sockaddr*) &src, sizeof(struct sockaddr_in)) != 0){ - std::string error ="socket bind failed: " + std::string(strerror(errno)); - throw (TRESTDAQException(error)); + src.sin_port = 0; + if (bind(client, (struct sockaddr*)&src, sizeof(struct sockaddr_in)) != 0) { + std::string error = "socket bind failed: " + std::string(strerror(errno)); + throw(TRESTDAQException(error)); } // Check receive socket size @@ -74,4 +73,3 @@ void TRESTDAQSocket::Clear() { remote_size = 0; target_adr = (unsigned char*)0; } - diff --git a/daq/TRESTDAQSocket.h b/daq/TRESTDAQSocket.h index f60ff6d..b7c59f6 100644 --- a/daq/TRESTDAQSocket.h +++ b/daq/TRESTDAQSocket.h @@ -2,12 +2,13 @@ #ifndef __TREST_DAQ_SOCKET__ #define __TREST_DAQ_SOCKET__ -#include +#include #include #include -#include -#include +#include + #include +#include #include #include "TRESTDAQException.h" @@ -16,7 +17,7 @@ class TRESTDAQSocket { public: - TRESTDAQSocket(){ }; + TRESTDAQSocket(){}; int client; struct sockaddr_in target; unsigned char* target_adr; @@ -31,5 +32,3 @@ class TRESTDAQSocket { }; #endif - - diff --git a/gui/TRestDAQGUI.cxx b/gui/TRestDAQGUI.cxx index f76c1eb..beba2fb 100755 --- a/gui/TRestDAQGUI.cxx +++ b/gui/TRestDAQGUI.cxx @@ -1,8 +1,10 @@ +#include "TRestDAQGUI.h" + +#include + #include -#include "TGMsgBox.h" -#include "TRestDAQGUI.h" #include "TRESTDAQManager.h" ClassImp(TRestDAQGUI); @@ -10,16 +12,15 @@ ClassImp(TRestDAQGUI); std::atomic TRestDAQGUI::exitGUI(false); std::atomic TRestDAQGUI::status(-1); - -TRestDAQGUI::TRestDAQGUI(const int& p, const int& q, TRestDAQGUIMetadata *mt) { +TRestDAQGUI::TRestDAQGUI(const int& p, const int& q, TRestDAQGUIMetadata* mt) { fMain = new TGMainFrame(gClient->GetRoot(), p, q, kHorizontalFrame); fMain->SetCleanup(kDeepCleanup); guiMetadata = mt; - - if(guiMetadata==nullptr) guiMetadata = new TRestDAQGUIMetadata(); - + + if (guiMetadata == nullptr) guiMetadata = new TRestDAQGUIMetadata(); + LoadLastSettings(); UpdateInputs(); @@ -71,24 +72,24 @@ TRestDAQGUI::TRestDAQGUI(const int& p, const int& q, TRestDAQGUIMetadata *mt) { pulses->GetXaxis()->SetTitle("TimeBin"); pulses->GetYaxis()->SetTitle("ADC"); - hitmap = new TH2Poly("Hitmap empty", "Hitmap empty",0,1,0,1); - #ifdef REST_DetectorLib - TFile *file = TFile::Open(guiMetadata->GetReadoutFile()); - if(file == nullptr || file->IsZombie() ) { - std::cout<<"Not valid file "<GetReadoutFile()<GetKey(guiMetadata->GetReadoutName()) == nullptr ) { - std::cout<<"Key "<< guiMetadata->GetReadoutName()<<" not found "<Close(); - } else { - fReadout = (TRestDetectorReadout *)file->Get(guiMetadata->GetReadoutName()); - if(fReadout){ - fReadout->PrintMetadata(); - TRestDetectorReadoutPlane* plane = &(*fReadout)[0]; - hitmap = plane->GetReadoutHistogram(); - } - file->Close(); + hitmap = new TH2Poly("Hitmap empty", "Hitmap empty", 0, 1, 0, 1); +#ifdef REST_DetectorLib + TFile* file = TFile::Open(guiMetadata->GetReadoutFile()); + if (file == nullptr || file->IsZombie()) { + std::cout << "Not valid file " << guiMetadata->GetReadoutFile() << std::endl; + } else if (file->GetKey(guiMetadata->GetReadoutName()) == nullptr) { + std::cout << "Key " << guiMetadata->GetReadoutName() << " not found " << std::endl; + file->Close(); + } else { + fReadout = (TRestDetectorReadout*)file->Get(guiMetadata->GetReadoutName()); + if (fReadout) { + fReadout->PrintMetadata(); + TRestDetectorReadoutPlane* plane = &(*fReadout)[0]; + hitmap = plane->GetReadoutHistogram(); } - #endif + file->Close(); + } +#endif fECanvas->GetCanvas()->cd(4); hitmap->Draw("COLZ0"); @@ -271,11 +272,7 @@ void TRestDAQGUI::SetButtons() { fVLeft->AddFrame(quitFrame, new TGLayoutHints(kLHintsCenterX | kFixedWidth, 1, 1, 1, 1)); } -void TRestDAQGUI::VerifyEventsEntry(){ - - nEventsEntry->SetText( std::to_string(std::atoi(nEventsEntry->GetText() ) ).c_str() ); - -} +void TRestDAQGUI::VerifyEventsEntry() { nEventsEntry->SetText(std::to_string(std::atoi(nEventsEntry->GetText())).c_str()); } void TRestDAQGUI::StartPressed() { int shmid; @@ -287,14 +284,14 @@ void TRestDAQGUI::StartPressed() { type = typeCombo->GetSelected(); for (const auto& [name, t] : daq_metadata_types::acqTypes_map) { if (type == static_cast(t)) { - std::cout<runType, name.c_str()); break; } } cfgFileName = cfgName->GetText(); - std::cout<cfgFile, cfgFileName.c_str()); nEvents = std::atoi(nEventsEntry->GetText()); @@ -316,37 +313,35 @@ void TRestDAQGUI::StopPressed() { } void TRestDAQGUI::StartUpPressed() { - startUpMain = new TGTransientFrame(gClient->GetRoot(), fMain, 400, 200); - startUpMain->DontCallClose(); // to avoid double deletions. + startUpMain->DontCallClose(); // to avoid double deletions. startUpMain->SetCleanup(kDeepCleanup); startUpMain->Resize(); - // position relative to the parent's window + // position relative to the parent's window startUpMain->CenterOnParent(); - int retval=0; + int retval = 0; startUpMain->Disconnect("CloseWindow()"); startUpMain->Connect("CloseWindow()", "TRestDAQGUI", this, "CloseStartUpWindow()"); - new TGMsgBox(gClient->GetRoot(), startUpMain, - "START UP", "Start up is only needed after power-cycle, do you want to continue?", - kMBIconExclamation, kMBYes| kMBNo, &retval); + new TGMsgBox(gClient->GetRoot(), startUpMain, "START UP", "Start up is only needed after power-cycle, do you want to continue?", + kMBIconExclamation, kMBYes | kMBNo, &retval); startUpMain->MapWindow(); - //gClient->WaitFor(startUpMain); + // gClient->WaitFor(startUpMain); - if(retval == kMBYes){ - int shmid; - TRESTDAQManager::sharedMemoryStruct* mem; + if (retval == kMBYes) { + int shmid; + TRESTDAQManager::sharedMemoryStruct* mem; if (!TRESTDAQManager::GetSharedMemory(shmid, &mem)) { - std::cerr << "Cannot get shared memory, please make sure that restDAQManager is running" << std::endl; - return; + std::cerr << "Cannot get shared memory, please make sure that restDAQManager is running" << std::endl; + return; } - cfgFileName = cfgName->GetText(); - std::cout<cfgFile, cfgFileName.c_str()); - mem->startUp = 1; - TRESTDAQManager::DetachSharedMemory(&mem); + cfgFileName = cfgName->GetText(); + std::cout << cfgFileName << std::endl; + sprintf(mem->cfgFile, cfgFileName.c_str()); + mem->startUp = 1; + TRESTDAQManager::DetachSharedMemory(&mem); } delete startUpMain; @@ -354,7 +349,7 @@ void TRestDAQGUI::StartUpPressed() { void TRestDAQGUI::cfgButtonPressed() { cfgMain = new TGTransientFrame(gClient->GetRoot(), fMain, 400, 200); - cfgMain->DontCallClose(); // to avoid double deletions. + cfgMain->DontCallClose(); // to avoid double deletions. cfgMain->Disconnect("CloseWindow()"); cfgMain->Connect("CloseWindow()", "TRestDAQGUI", this, "CloseCfgWindow()"); cfgMain->SetCleanup(kDeepCleanup); @@ -428,17 +423,16 @@ void TRestDAQGUI::SaveLastSettings() { } void TRestDAQGUI::UpdateInputs() { - - int shmid; - TRESTDAQManager::sharedMemoryStruct* mem; - if (!TRESTDAQManager::GetSharedMemory(shmid, &mem)) { + int shmid; + TRESTDAQManager::sharedMemoryStruct* mem; + if (!TRESTDAQManager::GetSharedMemory(shmid, &mem)) { std::cerr << "Cannot get shared memory, please make sure that restDAQManager is running" << std::endl; return; } - //Only update if is DAQ running - if(mem->status != 1){ - TRESTDAQManager::DetachSharedMemory(&mem); - return; + // Only update if is DAQ running + if (mem->status != 1) { + TRESTDAQManager::DetachSharedMemory(&mem); + return; } auto rT = daq_metadata_types::acqTypes_map.find(mem->runType); @@ -448,7 +442,6 @@ void TRestDAQGUI::UpdateInputs() { nEvents = mem->nEvents; TRESTDAQManager::DetachSharedMemory(&mem); - } void TRestDAQGUI::UpdateOutputs() { @@ -520,13 +513,13 @@ void TRestDAQGUI::SetUnknownState() { cfgButton->SetEnabled(kFALSE); } -bool TRestDAQGUI::GetDAQManagerParams(double &lastTimeUpdate) { +bool TRestDAQGUI::GetDAQManagerParams(double& lastTimeUpdate) { int shmid; TRESTDAQManager::sharedMemoryStruct* mem; if (!TRESTDAQManager::GetSharedMemory(shmid, &mem, 0, false)) { - if( (tNow - lastTimeUpdate) > 30 ){ - std::cerr << "Cannot get shared memory, please make sure that restDAQManager is running" << std::endl; - lastTimeUpdate = tNow; + if ((tNow - lastTimeUpdate) > 30) { + std::cerr << "Cannot get shared memory, please make sure that restDAQManager is running" << std::endl; + lastTimeUpdate = tNow; } return false; } @@ -543,8 +536,7 @@ bool TRestDAQGUI::GetDAQManagerParams(double &lastTimeUpdate) { } void TRestDAQGUI::UpdateParams() { - - double lastTimeUpdate = 0; + double lastTimeUpdate = 0; while (!exitGUI) { tNow = TRESTDAQ::getCurrentTime(); @@ -571,14 +563,12 @@ void TRestDAQGUI::UpdateParams() { } void TRestDAQGUI::READ() { - while (!exitGUI) { - - std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); if (status == 1) { int fSize = TRESTDAQManager::GetFileSize(runN); - if(fSize < guiMetadata->GetMinFileSize() )continue;//Wait till filesize is big enough + if (fSize < guiMetadata->GetMinFileSize()) continue; // Wait till filesize is big enough TFile f(runN.c_str()); if (f.IsZombie()) continue; @@ -616,7 +606,7 @@ void TRestDAQGUI::READ() { AnalyzeEvent(fEvent, timeUpdate); i++; } - std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME) ); + std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); tree->Refresh(); } f.Close(); @@ -646,8 +636,7 @@ void TRestDAQGUI::UpdateRate(const double& currentTimeEv, double& oldTimeEv, con } void TRestDAQGUI::AnalyzeEvent(TRestRawSignalEvent* fEvent, double& oldTimeUpdate) { - - bool updatePlots = tNow > (oldTimeUpdate + PLOTS_UPDATE_TIME ); + bool updatePlots = tNow > (oldTimeUpdate + PLOTS_UPDATE_TIME); if (updatePlots) { pulsesGraph.clear(); @@ -655,24 +644,23 @@ void TRestDAQGUI::AnalyzeEvent(TRestRawSignalEvent* fEvent, double& oldTimeUpdat int evAmplitude = 0; std::map hmap; - int color =1; + int color = 1; for (int s = 0; s < fEvent->GetNumberOfSignals(); s++) { TRestRawSignal* signal = fEvent->GetSignal(s); const double max = signal->GetAmplitudeFast(TVector2(guiMetadata->GetBaselineRange()), guiMetadata->GetSignalThreshold()); - if(max<=0)continue; + if (max <= 0) continue; - evAmplitude +=max; + evAmplitude += max; hmap[signal->GetID()] = max; - if (updatePlots) - pulsesGraph.emplace_back( signal->GetGraph(color)); + if (updatePlots) pulsesGraph.emplace_back(signal->GetGraph(color)); color++; } if (!hmap.empty() && evAmplitude > 0) FillHitmap(hmap); - if(evAmplitude > 0)spectrum->Fill(evAmplitude); + if (evAmplitude > 0) spectrum->Fill(evAmplitude); if (updatePlots) { if (meanRateGraph->GetN() > 0 && instantRateGraph->GetN() > 0) { @@ -689,12 +677,12 @@ void TRestDAQGUI::AnalyzeEvent(TRestRawSignalEvent* fEvent, double& oldTimeUpdat gr->Draw("SAME"); } - #ifdef REST_DetectorLib - if(fReadout){ +#ifdef REST_DetectorLib + if (fReadout) { fECanvas->GetCanvas()->cd(4); hitmap->Draw("COLZ0"); - } - #endif + } +#endif fECanvas->GetCanvas()->Update(); oldTimeUpdate = tNow; @@ -702,23 +690,23 @@ void TRestDAQGUI::AnalyzeEvent(TRestRawSignalEvent* fEvent, double& oldTimeUpdat } void TRestDAQGUI::FillHitmap(const std::map& hmap) { - #ifdef REST_DetectorLib - if(!fReadout)return; +#ifdef REST_DetectorLib + if (!fReadout) return; double posX = 0, posY = 0; int ampX = 0, ampY = 0; - Int_t readoutChannel = -1, readoutModule, planeID=0; + Int_t readoutChannel = -1, readoutModule, planeID = 0; TRestDetectorReadoutPlane* plane = &(*fReadout)[0]; for (const auto& [sID, ampl] : hmap) { - fReadout->GetPlaneModuleChannel(sID, planeID, readoutModule, readoutChannel); - if (readoutChannel==-1) continue; + fReadout->GetPlaneModuleChannel(sID, planeID, readoutModule, readoutChannel); + if (readoutChannel == -1) continue; Double_t x = plane->GetX(readoutModule, readoutChannel); Double_t y = plane->GetY(readoutModule, readoutChannel); - if ( TMath::IsNaN(y) ) { + if (TMath::IsNaN(y)) { posX += ampl * x; ampX += ampl; - } else if ( TMath::IsNaN(x) ) { + } else if (TMath::IsNaN(x)) { posY += ampl * y; ampY += ampl; } @@ -729,5 +717,5 @@ void TRestDAQGUI::FillHitmap(const std::map& hmap) { posX /= ampX; posY /= ampY; hitmap->Fill(posX, posY); - #endif +#endif } diff --git a/gui/TRestDAQGUI.h b/gui/TRestDAQGUI.h index 16c4ca8..f8e8aca 100755 --- a/gui/TRestDAQGUI.h +++ b/gui/TRestDAQGUI.h @@ -24,6 +24,8 @@ #include #include #include +#include +#include #include #include #include @@ -31,20 +33,15 @@ #include #include #include - #include #include #include - -#include "TRestRawSignalEvent.h" -#include "TRestDAQGUIMetadata.h" #ifdef REST_DetectorLib #include "TRestDetectorReadout.h" #endif - -constexpr int PLOTS_UPDATE_TIME = 5;//Seconds to update the plots -constexpr int SLEEP_TIME = 500;//Miliseconds to sleep +constexpr int PLOTS_UPDATE_TIME = 5; // Seconds to update the plots +constexpr int SLEEP_TIME = 500; // Milliseconds to sleep class TRestDAQGUI { public: @@ -52,12 +49,12 @@ class TRestDAQGUI { TGVerticalFrame* fVLeft; static inline TGTextButton *startButton, *stopButton, *quitButton, *cfgButton, *startUpButton; TGLabel *runLabel, *cfgLabel, *typeLabel, *nEventsLabel; - static inline TGLabel *statusLabel,*counterLabel, *rateLabel; - static inline TGTextEntry* runName, *cfgName, *nEventsEntry; + static inline TGLabel *statusLabel, *counterLabel, *rateLabel; + static inline TGTextEntry *runName, *cfgName, *nEventsEntry; static inline TGComboBox* typeCombo; - static inline TRestDAQGUIMetadata *guiMetadata; + static inline TRestDAQGUIMetadata* guiMetadata; TGFileContainer* fContents; TGTransientFrame* cfgMain; @@ -83,7 +80,7 @@ class TRestDAQGUI { std::thread updateT, readerT; - TRestDAQGUI(const int& p, const int& q, TRestDAQGUIMetadata *mt); + TRestDAQGUI(const int& p, const int& q, TRestDAQGUIMetadata* mt); ~TRestDAQGUI(); // need to delete here created widgets void SetInputs(); @@ -95,12 +92,12 @@ class TRestDAQGUI { void ReadCfgFileName(); void VerifyEventsEntry(); - void CloseCfgWindow(){ - if(cfgMain)delete cfgMain; + void CloseCfgWindow() { + if (cfgMain) delete cfgMain; } - void CloseStartUpWindow(){ - if(startUpMain)delete startUpMain; + void CloseStartUpWindow() { + if (startUpMain) delete startUpMain; } void LoadLastSettings(); @@ -123,7 +120,7 @@ class TRestDAQGUI { static void AnalyzeEvent(TRestRawSignalEvent* fEvent, double& oldTimeUpdate); static void UpdateRate(const double& currentTimeEv, double& oldTimeEv, const int& currentEventCount, int& oldEventCount); - static bool GetDAQManagerParams(double &lastTimeUpdate); + static bool GetDAQManagerParams(double& lastTimeUpdate); const std::string lastSetFile = "DAQLastSettings.txt"; static std::atomic exitGUI; @@ -131,9 +128,9 @@ class TRestDAQGUI { static void FillHitmap(const std::map& hmap); - #ifdef REST_DetectorLib +#ifdef REST_DetectorLib static inline TRestDetectorReadout* fReadout = nullptr; - #endif +#endif ClassDef(TRestDAQGUI, 1) }; diff --git a/gui/TRestDAQGUIMetadata.cxx b/gui/TRestDAQGUIMetadata.cxx index 7bf5bb7..f325a54 100644 --- a/gui/TRestDAQGUIMetadata.cxx +++ b/gui/TRestDAQGUIMetadata.cxx @@ -21,7 +21,7 @@ *************************************************************************/ ///////////////////////////////////////////////////////////////////////// -/// TRestDAQGUIMetadata holds the required configuration to launch +/// TRestDAQGUIMetadata holds the required configuration to launch /// a Grafical User Interface for data acquisition aka TRestDAQGUI. /// The default initialization is used in case no TRestDAQGUIMetadata /// while a TRestDAQGUI is instanciated. @@ -36,9 +36,9 @@ /// * **minFileSize**: Minimum file size to start reading a root file (bytes) /// * **readoutFile**: File name (root) where the readout is stored /// * **readoutName**: Name of the readout stored in the root file. -/// +/// /// ### Examples -/// Give examples of usage and RML descriptions that can be tested. +/// Give examples of usage and RML descriptions that can be tested. /// \code /// /// @@ -52,33 +52,31 @@ /// /// /// \endcode -/// -/// +/// +/// ///---------------------------------------------------------------------- -/// -/// REST-for-Physics - Software for Rare Event Searches Toolkit -/// -/// History of developments: -/// +/// +/// REST-for-Physics - Software for Rare Event Searches Toolkit +/// +/// History of developments: +/// /// 2022-June: First implementation of TRestDAQGUIMetadata -/// JuanAn Garcia -/// -/// \class TRestDAQGUIMetadata +/// JuanAn Garcia +/// +/// \class TRestDAQGUIMetadata /// \author: JuanAn Garcia e-mail: juanangp@unizar.es -/// -///
-/// +/// +///
+/// #include "TRestDAQGUIMetadata.h" ClassImp(TRestDAQGUIMetadata); -/////////////////////////////////////////////// -/// \brief Default constructor -/// -TRestDAQGUIMetadata::TRestDAQGUIMetadata() { - Initialize(); -} +/////////////////////////////////////////////// +/// \brief Default constructor +/// +TRestDAQGUIMetadata::TRestDAQGUIMetadata() { Initialize(); } ///////////////////////////////////////////// /// \brief Constructor loading data from a config file @@ -89,17 +87,13 @@ TRestDAQGUIMetadata::TRestDAQGUIMetadata(const char* configFilename, std::string if (GetVerboseLevel() >= TRestStringOutput::REST_Verbose_Level::REST_Info) PrintMetadata(); } -/////////////////////////////////////////////// -/// \brief Default destructor -/// -TRestDAQGUIMetadata::~TRestDAQGUIMetadata() { -} - -/////////////////////////////////////////////// -/// \brief Function to initialize input/output event members and define -/// the section name -/// -void TRestDAQGUIMetadata::Initialize() { - SetSectionName(this->ClassName()); -} +/////////////////////////////////////////////// +/// \brief Default destructor +/// +TRestDAQGUIMetadata::~TRestDAQGUIMetadata() {} +/////////////////////////////////////////////// +/// \brief Function to initialize input/output event members and define +/// the section name +/// +void TRestDAQGUIMetadata::Initialize() { SetSectionName(this->ClassName()); } diff --git a/gui/TRestDAQGUIMetadata.h b/gui/TRestDAQGUIMetadata.h index 7555bf9..2037885 100644 --- a/gui/TRestDAQGUIMetadata.h +++ b/gui/TRestDAQGUIMetadata.h @@ -23,13 +23,12 @@ #ifndef REST_TRestDAQGUIMetadata #define REST_TRestDAQGUIMetadata -#include "TRestMetadata.h" +#include /// This class is meant to hold TRestDAQGUIMetadata for online visualization of the DAQ GUI /// Note that this class is not meant to be stored in any root file, just for GUI visualization class TRestDAQGUIMetadata : public TRestMetadata { - private: - + private: /// The range where the baseline range will be calculated TVector2 fBaseLineRange = TVector2(5, 55); @@ -43,40 +42,36 @@ class TRestDAQGUIMetadata : public TRestMetadata { Double_t fSpectraMax = 100000; /// Minimum file size to start reading a root file in bytes - int fMinFileSize = 15*1024; + int fMinFileSize = 15 * 1024; /// Name of the readout file if any TString fReadoutFile = ""; /// Name of the readout inside the file TString fReadoutName = ""; - void Initialize() override; -public: - - inline const TVector2 GetBaselineRange() const{ return fBaseLineRange; } + public: + inline const TVector2 GetBaselineRange() const { return fBaseLineRange; } inline const Double_t GetSignalThreshold() const { return fSignalThreshold; } inline const Int_t GetBinsSpectra() const { return fBinsSpectra; } inline const Double_t GetSpetraMax() const { return fSpectraMax; } inline const int GetMinFileSize() const { return fMinFileSize; } - inline const TString GetReadoutFile() const { return fReadoutFile;} - inline const TString GetReadoutName() const { return fReadoutName;} + inline const TString GetReadoutFile() const { return fReadoutFile; } + inline const TString GetReadoutName() const { return fReadoutName; } void PrintMetadata() override { TRestMetadata::PrintMetadata(); - RESTMetadata << "Baseline range : ( " << fBaseLineRange.X() << " , " << fBaseLineRange.Y() << " ) " - << RESTendl; + RESTMetadata << "Baseline range : ( " << fBaseLineRange.X() << " , " << fBaseLineRange.Y() << " ) " << RESTendl; RESTMetadata << "Signal threshold : " << fSignalThreshold << " sigmas" << RESTendl; RESTMetadata << "Bins Spectra : " << fBinsSpectra << RESTendl; RESTMetadata << "Spectra max: " << fSpectraMax << RESTendl; RESTMetadata << "Min file size: " << fMinFileSize << " bytes" << RESTendl; - RESTMetadata << "Readout file/name: " << fReadoutFile<<" "< Date: Wed, 26 Oct 2022 20:15:44 +0200 Subject: [PATCH 08/13] formatting --- CMakeLists.txt | 23 +++++++++-------------- gui/CMakeLists.txt | 1 + gui/TRestDAQGUI.cxx | 4 ++-- main.cxx | 2 +- 4 files changed, 13 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7488ee6..2212e4d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -70,23 +70,18 @@ add_executable(${EXECUTABLE_NAME} main.cxx) target_link_libraries(${EXECUTABLE_NAME} PUBLIC RESTDAQ RestDAQGUI ${LINK_LIBRARIES} ${ROOT_LIBRARIES} RestRaw PRIVATE CLI11::CLI11) target_include_directories(${EXECUTABLE_NAME} SYSTEM PUBLIC ${INCLUDE_DIRS}) -message(STATUS "include directories: ${INCLUDE_DIRS}") - -#---------------------------------------------------------------------------- -# Copy restDAQManager to the install directory install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin) -#---------------------------------------------------------------------------- -# Copy macros to the install directory -file(GLOB_RECURSE MAC "${CMAKE_CURRENT_SOURCE_DIR}/macros/*") -INSTALL(FILES ${MAC} DESTINATION ./macros/daq) - -#---------------------------------------------------------------------------- -# Install the executable to 'bin' directory under CMAKE_INSTALL_PREFIX -# -#install(TARGETS ${PROJECT_NAME} DESTINATION bin) - if (NOT ${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) set(package_added "${PROJECT_NAME}") set(package_added ${package_added} PARENT_SCOPE) endif () + +file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/examples + DESTINATION ${CMAKE_CURRENT_BINARY_DIR} + ) + +install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/examples/ + DESTINATION examples + COMPONENT install + ) diff --git a/gui/CMakeLists.txt b/gui/CMakeLists.txt index 8cc0981..2fe6e99 100644 --- a/gui/CMakeLists.txt +++ b/gui/CMakeLists.txt @@ -11,5 +11,6 @@ target_include_directories(RestDAQGUI PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${ROOT_ target_link_libraries(RestDAQGUI PUBLIC RESTDAQ ${LINK_LIBRARIES} RestRaw) install(TARGETS RestDAQGUI DESTINATION lib) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libTRestDAQGUI_rdict.pcm DESTINATION lib) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libTRestDAQGUIMetadata_rdict.pcm DESTINATION lib) diff --git a/gui/TRestDAQGUI.cxx b/gui/TRestDAQGUI.cxx index beba2fb..d81a2e1 100755 --- a/gui/TRestDAQGUI.cxx +++ b/gui/TRestDAQGUI.cxx @@ -292,7 +292,7 @@ void TRestDAQGUI::StartPressed() { cfgFileName = cfgName->GetText(); std::cout << cfgFileName << std::endl; - sprintf(mem->cfgFile, cfgFileName.c_str()); + sprintf(mem->cfgFile, "%s", cfgFileName.c_str()); nEvents = std::atoi(nEventsEntry->GetText()); mem->nEvents = nEvents; @@ -339,7 +339,7 @@ void TRestDAQGUI::StartUpPressed() { cfgFileName = cfgName->GetText(); std::cout << cfgFileName << std::endl; - sprintf(mem->cfgFile, cfgFileName.c_str()); + sprintf(mem->cfgFile, "%s", cfgFileName.c_str()); mem->startUp = 1; TRESTDAQManager::DetachSharedMemory(&mem); } diff --git a/main.cxx b/main.cxx index 268380f..e4f29e7 100644 --- a/main.cxx +++ b/main.cxx @@ -13,7 +13,7 @@ using namespace std; namespace fs = std::filesystem; -constexpr char* thisProgram = "restDAQManager"; +constexpr char* thisProgram = "restDAQ"; void signal_handler(int signum) { cout << "Signal handler for '" << signum << "'" << endl; From ebcb9d01118ebdcb890abee810d35c0bd940f4df Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Wed, 26 Oct 2022 22:05:55 +0200 Subject: [PATCH 09/13] add `source.sh` script when building as standalone --- CMakeLists.txt | 8 ++++++-- cmake/source.cmake | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 cmake/source.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 2212e4d..2418c22 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ project(restDAQ) set(CMAKE_CXX_STANDARD 17) if (${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) - # this will only be accessed when build restG4 as a standalone package, not when building the framework + # this will only be entered when build restDAQ as a standalone package, not when building the framework message(STATUS "${PROJECT_NAME} standalone build") CMAKE_MINIMUM_REQUIRED(VERSION 3.16) find_package(REST REQUIRED) @@ -28,7 +28,7 @@ execute_process(COMMAND root-config --cflags OUTPUT_VARIABLE ROOT_CFLAGS) string(STRIP ${ROOT_CFLAGS} ROOT_CFLAGS) message("-- Found ROOT version: ${ROOT_VERSION} with compilation flags: ${ROOT_CFLAGS} and libraries: ${ROOT_LIBRARIES}") -#Find REST +# Find REST if (NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX ${REST_PATH}) endif () @@ -85,3 +85,7 @@ install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/examples/ DESTINATION examples COMPONENT install ) + +if (${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + include(cmake/source.cmake) +endif () diff --git a/cmake/source.cmake b/cmake/source.cmake new file mode 100644 index 0000000..69df102 --- /dev/null +++ b/cmake/source.cmake @@ -0,0 +1,17 @@ +set(FILENAME ${CMAKE_BINARY_DIR}/source.sh) + +file(WRITE ${FILENAME}) +file(APPEND ${FILENAME} "#!/bin/bash\n\n") + +execute_process(COMMAND rest-config --prefix OUTPUT_VARIABLE REST_PREFIX) +string(REGEX REPLACE "\n$" "" REST_PREFIX ${REST_PREFIX}) +file(APPEND ${FILENAME} "source ${REST_PREFIX}/thisREST.sh\n") + +file(APPEND ${FILENAME} "\n") + +file(APPEND ${FILENAME} "export PATH=${CMAKE_INSTALL_PREFIX}/bin:$PATH\n") +file(APPEND ${FILENAME} "export LD_LIBRARY_PATH=${CMAKE_INSTALL_PREFIX}/lib:$LD_LIBRARY_PATH\n") + +file(APPEND ${FILENAME} "\n") + +install(FILES ${FILENAME} DESTINATION ${CMAKE_INSTALL_PREFIX}) From 56bd8143f3483085b04471cd077d35221ff57cc4 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Thu, 27 Oct 2022 09:43:53 +0200 Subject: [PATCH 10/13] use `nEvents` instead of `Nevents` --- examples/dummyDAQ.rml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/dummyDAQ.rml b/examples/dummyDAQ.rml index 80188e1..2493665 100644 --- a/examples/dummyDAQ.rml +++ b/examples/dummyDAQ.rml @@ -31,7 +31,7 @@ - + From a6d92736045f657745d225ed4e599a636b8aff25 Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Thu, 27 Oct 2022 10:17:34 +0200 Subject: [PATCH 11/13] formatting --- daq/TRESTDAQ.cxx | 24 +++--- daq/TRESTDAQ.h | 10 +-- daq/TRESTDAQFEMINOS.cxx | 26 +++---- daq/TRESTDAQFEMINOS.h | 14 ++-- daq/TRESTDAQManager.cxx | 160 ++++++++++++++++++++-------------------- daq/TRESTDAQManager.h | 12 +-- gui/TRestDAQGUI.cxx | 8 +- main.cxx | 8 +- 8 files changed, 135 insertions(+), 127 deletions(-) diff --git a/daq/TRESTDAQ.cxx b/daq/TRESTDAQ.cxx index 6b5f8d0..e9fa7bb 100644 --- a/daq/TRESTDAQ.cxx +++ b/daq/TRESTDAQ.cxx @@ -14,12 +14,14 @@ Author: JuanAn Garcia 18/05/2021 std::atomic TRESTDAQ::abrt(false); std::atomic TRESTDAQ::event_cnt(0); -TRESTDAQ::TRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM) { - restRun = rR; - daqMetadata = dM; +TRESTDAQ::TRESTDAQ(TRestRun* run, TRestRawDAQMetadata* sharedMemory) { + restRun = run; + daqMetadata = sharedMemory; verboseLevel = daqMetadata->GetVerboseLevel(); fSignalEvent = new TRestRawSignalEvent(); - if (restRun) restRun->AddEventBranch(fSignalEvent); + if (restRun) { + restRun->AddEventBranch(fSignalEvent); + } } TRESTDAQ::~TRESTDAQ() { @@ -31,16 +33,16 @@ Double_t TRESTDAQ::getCurrentTime() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000.0; } -void TRESTDAQ::FillTree(TRestRun* rR, TRestRawSignalEvent* sEvent) { - const double evTime = sEvent->GetTime(); +void TRESTDAQ::FillTree(TRestRun* run, TRestRawSignalEvent* event) { + const double evTime = event->GetTime(); - if (rR) { - rR->GetAnalysisTree()->SetEventInfo(sEvent); - rR->GetEventTree()->Fill(); - rR->GetAnalysisTree()->Fill(); + if (run) { + run->GetAnalysisTree()->SetEventInfo(event); + run->GetEventTree()->Fill(); + run->GetAnalysisTree()->Fill(); // AutoSave is needed to read and write at the same time if (event_cnt % 100 == 0 || (evTime - lastEvTime) > 10) { - rR->GetEventTree()->AutoSave("SaveSelf"); + run->GetEventTree()->AutoSave("SaveSelf"); } } event_cnt++; diff --git a/daq/TRESTDAQ.h b/daq/TRESTDAQ.h index eba41df..e119a78 100644 --- a/daq/TRESTDAQ.h +++ b/daq/TRESTDAQ.h @@ -23,7 +23,7 @@ To implement generic methods here class TRESTDAQ { public: - TRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM); + TRESTDAQ(TRestRun* run, TRestRawDAQMetadata* sharedMemory); ~TRESTDAQ(); // Pure virtual methods to start, stop and configure the DAQ @@ -41,10 +41,10 @@ class TRESTDAQ { static Double_t getCurrentTime(); - TRestRun* GetRestRun() { return restRun; } - TRestRawSignalEvent* GetSignalEvent() { return fSignalEvent; } - TRestRawDAQMetadata* GetDAQMetadata() { return daqMetadata; } - static void FillTree(TRestRun* rR, TRestRawSignalEvent* sEvent); + TRestRun* GetRestRun() const { return restRun; } + TRestRawSignalEvent* GetSignalEvent() const { return fSignalEvent; } + TRestRawDAQMetadata* GetDAQMetadata() const { return daqMetadata; } + static void FillTree(TRestRun* run, TRestRawSignalEvent* event); private: TRestRun* restRun; diff --git a/daq/TRESTDAQFEMINOS.cxx b/daq/TRESTDAQFEMINOS.cxx index 00e69dd..86be850 100644 --- a/daq/TRESTDAQFEMINOS.cxx +++ b/daq/TRESTDAQFEMINOS.cxx @@ -13,7 +13,7 @@ Author: JuanAn Garcia 18/08/2021 std::atomic TRESTDAQFEMINOS::stopReceiver(false); -TRESTDAQFEMINOS::TRESTDAQFEMINOS(TRestRun* rR, TRestRawDAQMetadata* dM) : TRESTDAQ(rR, dM) { initialize(); } +TRESTDAQFEMINOS::TRESTDAQFEMINOS(TRestRun* run, TRestRawDAQMetadata* metadata) : TRESTDAQ(run, metadata) { initialize(); } void TRESTDAQFEMINOS::initialize() { // FEMArray.reserve(GetDAQMetadata()->GetFECs().size() );//Reserve space for all the feminos inside the FEC @@ -33,7 +33,7 @@ void TRESTDAQFEMINOS::initialize() { } void TRESTDAQFEMINOS::startUp() { - std::cout << "Starting up readout" << std::endl; + std::cout << "Starting up FEMINOS" << std::endl; // FEC Power-down BroadcastCommand("power_inv 0", FEMArray); BroadcastCommand("fec_enable 0", FEMArray); @@ -280,19 +280,18 @@ void TRESTDAQFEMINOS::stopDAQ() { receiveThread.join(); eventBuilderThread.join(); - for (auto& FEM : FEMArray) FEM.Close(); + for (auto& FEM : FEMArray) { + FEM.Close(); + } } void TRESTDAQFEMINOS::BroadcastCommand(const char* cmd, std::vector& FEMA, bool wait) { for (auto& FEM : FEMA) { SendCommand(cmd, FEM, wait); } - - // if (verboseLevel >= REST_Debug)std::cout<<"Command sent "< lock(FEM.mutex_socket); if (sendto(FEM.client, cmd, strlen(cmd), 0, (struct sockaddr*)&(FEM.target), sizeof(struct sockaddr)) == -1) { std::string error = "sendto failed: " + std::string(strerror(errno)); @@ -300,9 +299,10 @@ void TRESTDAQFEMINOS::SendCommand(const char* cmd, FEMProxy& FEM, bool wait) { } lock.unlock(); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) - std::cout << "FEM " << FEM.fecMetadata.id << " Command sent " << cmd << std::endl; - + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug || true) { + std::cout << "Sent command '" << cmd << "' to FEM " << FEM.fecMetadata.id << " with IP " + << "" << std::endl; + } if (wait) { // lock.lock(); FEM.cmd_sent++; @@ -402,7 +402,7 @@ void TRESTDAQFEMINOS::ReceiveThread(std::vector* FEMA) { } } -void TRESTDAQFEMINOS::EventBuilderThread(std::vector* FEMA, TRestRun* rR, TRestRawSignalEvent* sEvent) { +void TRESTDAQFEMINOS::EventBuilderThread(std::vector* FEMA, TRestRun* run, TRestRawSignalEvent* sEvent) { sEvent->Initialize(); uint32_t ev_count; @@ -434,10 +434,10 @@ void TRESTDAQFEMINOS::EventBuilderThread(std::vector* FEMA, TRestRun* } if (newEvent && !pendingEvent) { // Save Event if closed - if (rR) { + if (run) { sEvent->SetID(ev_count); - sEvent->SetTime(rR->GetStartTimestamp() + (double)ts * 2E-8); - FillTree(rR, sEvent); + sEvent->SetTime(run->GetStartTimestamp() + (double)ts * 2E-8); + FillTree(run, sEvent); sEvent->Initialize(); newEvent = false; if (event_cnt % 100 == 0) std::cout << "Events " << event_cnt << std::endl; diff --git a/daq/TRESTDAQFEMINOS.h b/daq/TRESTDAQFEMINOS.h index 1b4302b..a559a74 100644 --- a/daq/TRESTDAQFEMINOS.h +++ b/daq/TRESTDAQFEMINOS.h @@ -38,17 +38,17 @@ class FEMProxy : public TRESTDAQSocket { class TRESTDAQFEMINOS : public TRESTDAQ { public: - TRESTDAQFEMINOS(TRestRun* rR, TRestRawDAQMetadata* dM); + TRESTDAQFEMINOS(TRestRun* run, TRestRawDAQMetadata* metadata); - virtual void configure(); - virtual void startDAQ(); - virtual void stopDAQ(); - virtual void initialize(); - virtual void startUp(); + void configure() override; + void startDAQ() override; + void stopDAQ() override; + void initialize() override; + void startUp() override; static void ReceiveThread(std::vector* FEMA); static void ReceiveBuffer(FEMProxy& FEM); - static void EventBuilderThread(std::vector* FEMA, TRestRun* rR, TRestRawSignalEvent* sEvent); + static void EventBuilderThread(std::vector* FEMA, TRestRun* run, TRestRawSignalEvent* sEvent); static void waitForCmd(FEMProxy& FEM); static std::atomic stopReceiver; diff --git a/daq/TRESTDAQManager.cxx b/daq/TRESTDAQManager.cxx index bf6cef0..dafe2f3 100644 --- a/daq/TRESTDAQManager.cxx +++ b/daq/TRESTDAQManager.cxx @@ -18,10 +18,12 @@ Control data acquisition via shared memory, should be always running #include "TRESTDAQDummy.h" #include "TRESTDAQFEMINOS.h" +using namespace std; + TRESTDAQManager::TRESTDAQManager() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; - if (!GetSharedMemory(shmid, &sharedMemory, IPC_CREAT | 0666)) exit(1); + if (!GetSharedMemory(sharedMemoryID, &sharedMemory, IPC_CREAT | 0666)) exit(1); InitializeSharedMemory(sharedMemory); PrintSharedMemory(sharedMemory); @@ -29,36 +31,36 @@ TRESTDAQManager::TRESTDAQManager() { } TRESTDAQManager::~TRESTDAQManager() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; - if (GetSharedMemory(shmid, &sharedMemory)) { + if (GetSharedMemory(sharedMemoryID, &sharedMemory)) { std::cout << "Destroying shared memory" << std::endl; DetachSharedMemory(&sharedMemory); - shmctl(shmid, IPC_RMID, NULL); + shmctl(sharedMemoryID, IPC_RMID, nullptr); } } void TRESTDAQManager::startUp() { std::cout << __PRETTY_FUNCTION__ << std::endl; - int shmid; - sharedMemoryStruct* sM; - if (!GetSharedMemory(shmid, &sM)) return; + int shareMemoryID; + sharedMemoryStruct* sharedMemory; + if (!GetSharedMemory(shareMemoryID, &sharedMemory)) return; - if (!TRestTools::fileExists(sM->cfgFile)) { - std::cout << "File " << sM->cfgFile << " not found, please provide existing config file" << std::endl; - DetachSharedMemory(&sM); + if (!TRestTools::fileExists(sharedMemory->configFilename)) { + std::cout << "File '" << sharedMemory->configFilename << "' not found, please provide existing config file" << std::endl; + DetachSharedMemory(&sharedMemory); return; } - TRestRawDAQMetadata daqMetadata(sM->cfgFile); + TRestRawDAQMetadata daqMetadata(sharedMemory->configFilename); - sM->status = 1; - DetachSharedMemory(&sM); + sharedMemory->status = 1; + DetachSharedMemory(&sharedMemory); try { auto daq = GetTRESTDAQ(nullptr, &daqMetadata); - if (daq) { + if (daq != nullptr) { daq->startUp(); daq->stopDAQ(); } @@ -69,10 +71,10 @@ void TRESTDAQManager::startUp() { } } -std::unique_ptr TRESTDAQManager::GetTRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM) { +std::unique_ptr TRESTDAQManager::GetTRESTDAQ(TRestRun* run, TRestRawDAQMetadata* metadata) { std::unique_ptr daq(nullptr); - std::string electronicsType(dM->GetElectronicsType()); + std::string electronicsType(metadata->GetElectronicsType()); auto eT = daq_metadata_types::electronicsTypes_map.find(electronicsType); if (eT == daq_metadata_types::electronicsTypes_map.end()) { std::cout << "Electronics type " << electronicsType << " not found, skipping " << std::endl; @@ -82,56 +84,58 @@ std::unique_ptr TRESTDAQManager::GetTRESTDAQ(TRestRun* rR, TRestRawDAQ } if (eT->second == daq_metadata_types::electronicsTypes::DUMMY) { - daq = std::make_unique(rR, dM); + daq = std::make_unique(run, metadata); } else if (eT->second == daq_metadata_types::electronicsTypes::DCC) { - daq = std::make_unique(rR, dM); + daq = std::make_unique(run, metadata); } else if (eT->second == daq_metadata_types::electronicsTypes::FEMINOS) { - daq = std::make_unique(rR, dM); + daq = std::make_unique(run, metadata); } else { std::cout << electronicsType << " not implemented, skipping..." << std::endl; + cerr << "Error: Invalid electronics type " << electronicsType << endl; + return 1; } return daq; } void TRESTDAQManager::dataTaking() { - int shmid; - sharedMemoryStruct* sM; - if (!GetSharedMemory(shmid, &sM)) return; + int sharedMemoryID; + sharedMemoryStruct* sharedMemory; + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) return; - if (!TRestTools::fileExists(sM->cfgFile)) { - std::cout << "File " << sM->cfgFile << " not found, please provide existing config file" << std::endl; - DetachSharedMemory(&sM); + if (!TRestTools::fileExists(sharedMemory->configFilename)) { + std::cout << "File '" << sharedMemory->configFilename << "' not found, please provide existing config file" << std::endl; + DetachSharedMemory(&sharedMemory); return; } - TRestRawDAQMetadata daqMetadata(sM->cfgFile); + TRestRawDAQMetadata daqMetadata(sharedMemory->configFilename); - auto rT = daq_metadata_types::acqTypes_map.find(sM->runType); + auto rT = daq_metadata_types::acqTypes_map.find(sharedMemory->runType); if (rT != daq_metadata_types::acqTypes_map.end()) { - daqMetadata.SetAcquisitionType(sM->runType); + daqMetadata.SetAcquisitionType(sharedMemory->runType); } else if ((rT = daq_metadata_types::acqTypes_map.find(daqMetadata.GetAcquisitionType().Data())) != daq_metadata_types::acqTypes_map.end()) { std::cout << "Warning: Acquisition type not found in shared memory, assuming the " << daqMetadata.GetAcquisitionType().Data() << " from config file" << std::endl; - sprintf(sM->runType, "%s", daqMetadata.GetAcquisitionType().Data()); + sprintf(sharedMemory->runType, "%s", daqMetadata.GetAcquisitionType().Data()); } else { - std::cout << "Acquisition type " << sM->runType << " not found, skipping " << std::endl; + std::cout << "Acquisition type " << sharedMemory->runType << " not found, skipping " << std::endl; std::cout << "Valid acquisition types:" << std::endl; for (const auto& [name, t] : daq_metadata_types::acqTypes_map) std::cout << (int)t << " " << name << std::endl; - DetachSharedMemory(&sM); + DetachSharedMemory(&sharedMemory); return; } - if (sM->nEvents > -1) { - daqMetadata.SetNEvents(sM->nEvents); - std::cout << "Setting " << sM->nEvents << " events to be acquired" << std::endl; + if (sharedMemory->nEvents > -1) { + daqMetadata.SetNEvents(sharedMemory->nEvents); + std::cout << "Setting " << sharedMemory->nEvents << " events to be acquired" << std::endl; } else { std::cout << "Setting " << daqMetadata.GetNEvents() << " events to be acquired from config file" << std::endl; - sM->nEvents = daqMetadata.GetNEvents(); + sharedMemory->nEvents = daqMetadata.GetNEvents(); } TRestRun restRun; - restRun.LoadConfigFromFile(sM->cfgFile); + restRun.LoadConfigFromFile(sharedMemory->configFilename); daqMetadata.PrintMetadata(); TString rTag = restRun.GetRunTag(); @@ -140,13 +144,13 @@ void TRESTDAQManager::dataTaking() { restRun.SetRunType(daqMetadata.GetAcquisitionType()); restRun.AddMetadata(&daqMetadata); restRun.FormOutputFile(); - sprintf(sM->runName, "%s", restRun.GetOutputFileName().Data()); - std::cout << "Run " << sM->runName << " " << restRun.GetOutputFileName() << std::endl; + sprintf(sharedMemory->runName, "%s", restRun.GetOutputFileName().Data()); + std::cout << "Run " << sharedMemory->runName << " " << restRun.GetOutputFileName() << std::endl; restRun.SetStartTimeStamp(TRESTDAQ::getCurrentTime()); restRun.PrintMetadata(); - sM->status = 1; - DetachSharedMemory(&sM); + sharedMemory->status = 1; + DetachSharedMemory(&sharedMemory); std::thread abrtT(AbortThread); @@ -177,17 +181,17 @@ void TRESTDAQManager::dataTaking() { } void TRESTDAQManager::StopRun() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; - if (!GetSharedMemory(shmid, &sharedMemory)) return; + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) return; sharedMemory->abortRun = 1; shmdt((sharedMemoryStruct*)sharedMemory); } void TRESTDAQManager::ExitManager() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; - if (!GetSharedMemory(shmid, &sharedMemory)) return; + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) return; sharedMemory->abortRun = 1; sharedMemory->exitManager = 1; PrintSharedMemory(sharedMemory); @@ -195,11 +199,11 @@ void TRESTDAQManager::ExitManager() { } void TRESTDAQManager::run() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; bool exitMan = false; do { - if (!GetSharedMemory(shmid, &sharedMemory)) { + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) { break; } exitMan = sharedMemory->exitManager; @@ -207,7 +211,7 @@ void TRESTDAQManager::run() { if (sharedMemory->startUp == 1) { DetachSharedMemory(&sharedMemory); startUp(); - if (!GetSharedMemory(shmid, &sharedMemory)) { + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) { break; } sharedMemory->startUp = 0; @@ -222,7 +226,7 @@ void TRESTDAQManager::run() { dataTaking(); - if (!GetSharedMemory(shmid, &sharedMemory)) { + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) { break; } sharedMemory->status = 0; @@ -234,45 +238,45 @@ void TRESTDAQManager::run() { } while (!exitMan); } -bool TRESTDAQManager::GetSharedMemory(int& sid, sharedMemoryStruct** sM, int flag, bool verbose) { - if ((sid = shmget(TRESTDAQManager::key, sizeof(sharedMemoryStruct), flag)) == -1) { +bool TRESTDAQManager::GetSharedMemory(int& sharedMemoryID, sharedMemoryStruct** sharedMemory, int flag, bool verbose) { + if ((sharedMemoryID = shmget(TRESTDAQManager::key, sizeof(sharedMemoryStruct), flag)) == -1) { if (verbose) std::cerr << "Error while creating shared memory (shmget) " << std::strerror(errno) << std::endl; return false; } - *sM = (sharedMemoryStruct*)shmat(sid, NULL, 0); - if (*sM == (sharedMemoryStruct*)-1) { + *sharedMemory = (sharedMemoryStruct*)shmat(sharedMemoryID, nullptr, 0); + if (*sharedMemory == (sharedMemoryStruct*)-1) { std::cerr << "Error while creating shared memory (shmat) " << std::strerror(errno) << std::endl; return false; } return true; } -void TRESTDAQManager::DetachSharedMemory(sharedMemoryStruct** sM) { shmdt((sharedMemoryStruct*)*sM); } - -void TRESTDAQManager::PrintSharedMemory(sharedMemoryStruct* sM) { - std::cout << "Cfg File: " << sM->cfgFile << std::endl; - std::cout << "Status: " << sM->status << std::endl; - std::cout << "StartDAQ: " << sM->startDAQ << std::endl; - std::cout << "RunType: " << sM->runType << std::endl; - std::cout << "AbortRun: " << sM->abortRun << std::endl; - std::cout << "Event count: " << sM->eventCount << std::endl; - std::cout << "Number of events to acquire: " << sM->nEvents << std::endl; - std::cout << "RunName: " << sM->runName << std::endl; - std::cout << "Exit Manager: " << sM->exitManager << std::endl; +void TRESTDAQManager::DetachSharedMemory(sharedMemoryStruct** sharedMemory) { shmdt((sharedMemoryStruct*)*sharedMemory); } + +void TRESTDAQManager::PrintSharedMemory(sharedMemoryStruct* sharedMemory) { + std::cout << "Config file: " << sharedMemory->configFilename << std::endl; + std::cout << "Status: " << sharedMemory->status << std::endl; + std::cout << "StartDAQ: " << sharedMemory->startDAQ << std::endl; + std::cout << "RunType: " << sharedMemory->runType << std::endl; + std::cout << "AbortRun: " << sharedMemory->abortRun << std::endl; + std::cout << "Event count: " << sharedMemory->eventCount << std::endl; + std::cout << "Number of events to acquire: " << sharedMemory->nEvents << std::endl; + std::cout << "RunName: " << sharedMemory->runName << std::endl; + std::cout << "Exit Manager: " << sharedMemory->exitManager << std::endl; } -void TRESTDAQManager::InitializeSharedMemory(sharedMemoryStruct* sM) { - sprintf(sM->cfgFile, "none"); - sprintf(sM->runType, "none"); - sprintf(sM->runName, "none"); - sM->startDAQ = 0; - sM->startUp = 0; - sM->status = 0; - sM->eventCount = 0; - sM->nEvents = -1; - sM->exitManager = 0; - sM->abortRun = 0; +void TRESTDAQManager::InitializeSharedMemory(sharedMemoryStruct* sharedMemory) { + sprintf(sharedMemory->configFilename, "none"); + sprintf(sharedMemory->runType, "none"); + sprintf(sharedMemory->runName, "none"); + sharedMemory->startDAQ = 0; + sharedMemory->startUp = 0; + sharedMemory->status = 0; + sharedMemory->eventCount = 0; + sharedMemory->nEvents = -1; + sharedMemory->exitManager = 0; + sharedMemory->abortRun = 0; } int TRESTDAQManager::GetFileSize(const std::string& filename) { @@ -282,12 +286,12 @@ int TRESTDAQManager::GetFileSize(const std::string& filename) { } void TRESTDAQManager::AbortThread() { - int shmid; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; bool abrt = false; do { - if (!GetSharedMemory(shmid, &sharedMemory)) break; + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) break; abrt = sharedMemory->abortRun; sharedMemory->eventCount = TRESTDAQ::event_cnt; DetachSharedMemory(&sharedMemory); diff --git a/daq/TRESTDAQManager.h b/daq/TRESTDAQManager.h index 49e8685..5feab64 100644 --- a/daq/TRESTDAQManager.h +++ b/daq/TRESTDAQManager.h @@ -29,7 +29,7 @@ class TRESTDAQManager { // Shared memory struct sharedMemoryStruct { - char cfgFile[1024]; + char configFilename[1024]; char runType[256]; char runName[1024]; int startDAQ; @@ -43,13 +43,13 @@ class TRESTDAQManager { void dataTaking(); void startUp(); - std::unique_ptr GetTRESTDAQ(TRestRun* rR, TRestRawDAQMetadata* dM); + static std::unique_ptr GetTRESTDAQ(TRestRun* run, TRestRawDAQMetadata* metadata); // Shared Memory - static void InitializeSharedMemory(sharedMemoryStruct* sM); - static void PrintSharedMemory(sharedMemoryStruct* sM); - static bool GetSharedMemory(int& sid, sharedMemoryStruct** sM, int flag = 0, bool verbose = true); - static void DetachSharedMemory(sharedMemoryStruct** sM); + static void InitializeSharedMemory(sharedMemoryStruct* sharedMemory); + static void PrintSharedMemory(sharedMemoryStruct* sharedMemory); + static bool GetSharedMemory(int& sharedMemoryID, sharedMemoryStruct** sharedMemory, int flag = 0, bool verbose = true); + static void DetachSharedMemory(sharedMemoryStruct** sharedMemory); static int GetFileSize(const std::string& filename); diff --git a/gui/TRestDAQGUI.cxx b/gui/TRestDAQGUI.cxx index d81a2e1..040783c 100755 --- a/gui/TRestDAQGUI.cxx +++ b/gui/TRestDAQGUI.cxx @@ -285,14 +285,14 @@ void TRestDAQGUI::StartPressed() { for (const auto& [name, t] : daq_metadata_types::acqTypes_map) { if (type == static_cast(t)) { std::cout << name << std::endl; - sprintf(mem->runType, name.c_str()); + sprintf(mem->runType, "%s", name.c_str()); break; } } cfgFileName = cfgName->GetText(); std::cout << cfgFileName << std::endl; - sprintf(mem->cfgFile, "%s", cfgFileName.c_str()); + sprintf(mem->configFilename, "%s", cfgFileName.c_str()); nEvents = std::atoi(nEventsEntry->GetText()); mem->nEvents = nEvents; @@ -339,7 +339,7 @@ void TRestDAQGUI::StartUpPressed() { cfgFileName = cfgName->GetText(); std::cout << cfgFileName << std::endl; - sprintf(mem->cfgFile, "%s", cfgFileName.c_str()); + sprintf(mem->configFilename, "%s", cfgFileName.c_str()); mem->startUp = 1; TRESTDAQManager::DetachSharedMemory(&mem); } @@ -438,7 +438,7 @@ void TRestDAQGUI::UpdateInputs() { auto rT = daq_metadata_types::acqTypes_map.find(mem->runType); if (rT != daq_metadata_types::acqTypes_map.end()) type = (int)rT->second; - cfgFileName = mem->cfgFile; + cfgFileName = mem->configFilename; nEvents = mem->nEvents; TRESTDAQManager::DetachSharedMemory(&mem); diff --git a/main.cxx b/main.cxx index e4f29e7..34888e3 100644 --- a/main.cxx +++ b/main.cxx @@ -141,25 +141,27 @@ int main(int argc, char** argv) { int shareMemoryID; TRESTDAQManager::sharedMemoryStruct* sharedMemory; if (!TRESTDAQManager::GetSharedMemory(shareMemoryID, &sharedMemory)) { - cerr << "Cannot get shared memory!!" << endl; + cerr << "Error accessing shared memory" << endl; return 1; } char* fullPath = realpath(configFilename.c_str(), nullptr); if (fullPath) { cout << "Full path: " << fullPath << endl; - sprintf(sharedMemory->cfgFile, "%s", fullPath); + sprintf(sharedMemory->configFilename, "%s", fullPath); } else { - sprintf(sharedMemory->cfgFile, "%s", configFilename.c_str()); + sprintf(sharedMemory->configFilename, "%s", configFilename.c_str()); } TRESTDAQManager::DetachSharedMemory(&sharedMemory); if (startupElectronics) { cout << "Attempting electronics startup" << endl; daqManager.startUp(); + return 1; } else { daqManager.dataTaking(); } } else { cout << "Starting infinite loop" << endl; + return 1; daqManager.run(); } } From 275abe6916712d0cef79313942787af42609d7fa Mon Sep 17 00:00:00 2001 From: Luis Obis Date: Thu, 27 Oct 2022 11:38:18 +0200 Subject: [PATCH 12/13] add initialization and update timeout logic --- daq/TRESTDAQ.h | 5 ++++ daq/TRESTDAQFEMINOS.cxx | 55 ++++++++++++++++++++++++++++++----------- daq/TRESTDAQFEMINOS.h | 4 ++- daq/TRESTDAQManager.cxx | 50 ++++++++++++++++++++++++++++++++++--- daq/TRESTDAQManager.h | 3 +++ main.cxx | 28 ++++++++++++++------- 6 files changed, 116 insertions(+), 29 deletions(-) diff --git a/daq/TRESTDAQ.h b/daq/TRESTDAQ.h index e119a78..ca6cb6d 100644 --- a/daq/TRESTDAQ.h +++ b/daq/TRESTDAQ.h @@ -33,6 +33,11 @@ class TRESTDAQ { virtual void initialize() = 0; virtual void startUp(){}; + virtual bool Ping() const { + // To be overridden + return false; + }; + static std::atomic abrt; static std::atomic event_cnt; static inline double lastEvTime = 0; diff --git a/daq/TRESTDAQFEMINOS.cxx b/daq/TRESTDAQFEMINOS.cxx index 86be850..973a404 100644 --- a/daq/TRESTDAQFEMINOS.cxx +++ b/daq/TRESTDAQFEMINOS.cxx @@ -11,6 +11,8 @@ Author: JuanAn Garcia 18/08/2021 #include "FEMINOSPacket.h" +using namespace std; + std::atomic TRESTDAQFEMINOS::stopReceiver(false); TRESTDAQFEMINOS::TRESTDAQFEMINOS(TRestRun* run, TRestRawDAQMetadata* metadata) : TRESTDAQ(run, metadata) { initialize(); } @@ -33,6 +35,12 @@ void TRESTDAQFEMINOS::initialize() { } void TRESTDAQFEMINOS::startUp() { + std::cout << "Checking FEMINOS power status" << std::endl; + BroadcastCommand("fec_enable", FEMArray); + for (auto& FEM : FEMArray) { + cout << "FEM " << FEM.fecMetadata.id << " power status: " << FEM.cmd_rcv << endl; + } + std::cout << "Starting up FEMINOS" << std::endl; // FEC Power-down BroadcastCommand("power_inv 0", FEMArray); @@ -134,9 +142,9 @@ void TRESTDAQFEMINOS::configure() { SendCommand(cmd, FEM); for (int c = 0; c < 78; c++) { if (FEM.fecMetadata.asic_channelActive[a][c]) continue; - sprintf(cmd, "forceoff %d %d 0x1", a); + sprintf(cmd, "forceoff %d 0x1", a); SendCommand(cmd, FEM); - sprintf(cmd, "forceon %d %d 0x0", a); + sprintf(cmd, "forceon %d 0x0", a); SendCommand(cmd, FEM); } } @@ -299,9 +307,8 @@ void TRESTDAQFEMINOS::SendCommand(const char* cmd, FEMProxy& FEM, bool wait) { } lock.unlock(); - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug || true) { - std::cout << "Sent command '" << cmd << "' to FEM " << FEM.fecMetadata.id << " with IP " - << "" << std::endl; + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) { + std::cout << "Sent command '" << cmd << "' to FEM " << FEM.fecMetadata.id << std::endl; } if (wait) { // lock.lock(); @@ -311,22 +318,26 @@ void TRESTDAQFEMINOS::SendCommand(const char* cmd, FEMProxy& FEM, bool wait) { } } -void TRESTDAQFEMINOS::waitForCmd(FEMProxy& FEM) { - int timeout = 0; +bool TRESTDAQFEMINOS::waitForCmd(FEMProxy& FEM, int timeoutMillis) { bool condition; - + int timeWaitedMillis = 0; + int timeStepMillis = 100; do { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + std::this_thread::sleep_for(std::chrono::milliseconds(timeStepMillis)); + timeWaitedMillis += timeStepMillis; std::unique_lock lock(FEM.mutex_socket); condition = (FEM.cmd_sent > FEM.cmd_rcv); lock.unlock(); - timeout++; - } while (condition && timeout < 10); - - if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) - std::cout << "Cmd sent " << FEM.cmd_sent << " Cmd Received: " << FEM.cmd_rcv << std::endl; + } while (condition && timeWaitedMillis < timeoutMillis); - if (timeout >= 10) std::cout << "Cmd timeout " << std::endl; + if (timeWaitedMillis >= timeoutMillis) { + std::cout << "Cmd '" << FEM.cmd_sent << "' timeout" << std::endl; + return false; + } + if (verboseLevel >= TRestStringOutput::REST_Verbose_Level::REST_Debug) { + std::cout << "Cmd sent '" << FEM.cmd_sent << "' Cmd Received: " << FEM.cmd_rcv << std::endl; + } + return true; } void TRESTDAQFEMINOS::ReceiveThread(std::vector* FEMA) { @@ -445,3 +456,17 @@ void TRESTDAQFEMINOS::EventBuilderThread(std::vector* FEMA, TRestRun* } } } + +bool TRESTDAQFEMINOS::Ping() const { + bool result = true; + for (auto fec : GetDAQMetadata()->GetFECs()) { + const auto ip = fec.ip; + const auto ipString = to_string(ip[0]) + "." + to_string(ip[1]) + "." + to_string(ip[2]) + "." + to_string(ip[3]); + const string command = "ping -c1 -s1 " + ipString + " > /dev/null 2>&1"; + if (system(command.c_str()) != 0) { + cout << "ping failed for ip '" << ipString << "'" << endl; + result = false; + } + } + return result; +} diff --git a/daq/TRESTDAQFEMINOS.h b/daq/TRESTDAQFEMINOS.h index a559a74..76f0d9a 100644 --- a/daq/TRESTDAQFEMINOS.h +++ b/daq/TRESTDAQFEMINOS.h @@ -46,10 +46,12 @@ class TRESTDAQFEMINOS : public TRESTDAQ { void initialize() override; void startUp() override; + bool Ping() const override; + static void ReceiveThread(std::vector* FEMA); static void ReceiveBuffer(FEMProxy& FEM); static void EventBuilderThread(std::vector* FEMA, TRestRun* run, TRestRawSignalEvent* sEvent); - static void waitForCmd(FEMProxy& FEM); + static bool waitForCmd(FEMProxy& FEM, int timeoutMillis = 10000); static std::atomic stopReceiver; inline static std::mutex mutex; diff --git a/daq/TRESTDAQManager.cxx b/daq/TRESTDAQManager.cxx index dafe2f3..d9060b7 100644 --- a/daq/TRESTDAQManager.cxx +++ b/daq/TRESTDAQManager.cxx @@ -43,9 +43,9 @@ TRESTDAQManager::~TRESTDAQManager() { void TRESTDAQManager::startUp() { std::cout << __PRETTY_FUNCTION__ << std::endl; - int shareMemoryID; + int sharedMemoryID; sharedMemoryStruct* sharedMemory; - if (!GetSharedMemory(shareMemoryID, &sharedMemory)) return; + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) return; if (!TRestTools::fileExists(sharedMemory->configFilename)) { std::cout << "File '" << sharedMemory->configFilename << "' not found, please provide existing config file" << std::endl; @@ -92,7 +92,7 @@ std::unique_ptr TRESTDAQManager::GetTRESTDAQ(TRestRun* run, TRestRawDA } else { std::cout << electronicsType << " not implemented, skipping..." << std::endl; cerr << "Error: Invalid electronics type " << electronicsType << endl; - return 1; + exit(1); } return daq; @@ -139,7 +139,9 @@ void TRESTDAQManager::dataTaking() { daqMetadata.PrintMetadata(); TString rTag = restRun.GetRunTag(); - if (rTag == "Null" || rTag == "") restRun.SetRunTag(daqMetadata.GetTitle()); + if (rTag == "Null" || rTag == "") { + restRun.SetRunTag(daqMetadata.GetTitle()); + } restRun.SetRunType(daqMetadata.GetAcquisitionType()); restRun.AddMetadata(&daqMetadata); @@ -300,3 +302,43 @@ void TRESTDAQManager::AbortThread() { TRESTDAQ::abrt = true; } + +bool TRESTDAQManager::Initialize() const { + cout << "Initializing TRESTDAQManager. Checking for connection to DAQ" << endl; + + int sharedMemoryID; + sharedMemoryStruct* sharedMemory; + + if (!GetSharedMemory(sharedMemoryID, &sharedMemory)) { + cout << "Error getting shared memory" << endl; + return false; + } + + if (!TRestTools::fileExists(sharedMemory->configFilename)) { + std::cout << "File '" << sharedMemory->configFilename << "' not found, please provide existing config file" << std::endl; + DetachSharedMemory(&sharedMemory); + return false; + } + + TRestRawDAQMetadata daqMetadata(sharedMemory->configFilename); + + sharedMemory->status = 1; + + bool result = true; + auto daq = GetTRESTDAQ(nullptr, &daqMetadata); + if (daq == nullptr) { + std::cout << "Error while initializing DAQ" << std::endl; + result = false; + } + if (!daq->Ping()) { + cout << "Error pinging DAQ. Please check networking configuration" << endl; + result = false; + } + if (result) { + cout << "DAQ connection established" << endl; + } else { + cout << "Error establishing DAQ connection" << endl; + } + DetachSharedMemory(&sharedMemory); + return result; +} diff --git a/daq/TRESTDAQManager.h b/daq/TRESTDAQManager.h index 5feab64..d9cbd04 100644 --- a/daq/TRESTDAQManager.h +++ b/daq/TRESTDAQManager.h @@ -43,8 +43,11 @@ class TRESTDAQManager { void dataTaking(); void startUp(); + static std::unique_ptr GetTRESTDAQ(TRestRun* run, TRestRawDAQMetadata* metadata); + bool Initialize() const; + // Shared Memory static void InitializeSharedMemory(sharedMemoryStruct* sharedMemory); static void PrintSharedMemory(sharedMemoryStruct* sharedMemory); diff --git a/main.cxx b/main.cxx index 34888e3..ab99734 100644 --- a/main.cxx +++ b/main.cxx @@ -96,6 +96,7 @@ int main(int argc, char** argv) { run->add_option("--stop", "Stop previous acquisition process if it exists")->expected(0); run->add_option("--startup", "Perform startup of electronics")->expected(0); run->add_option("--exit", "Perform startup of electronics")->expected(0); + run->add_option("--verbose,-v", "Verbose mode")->expected(0); app.require_subcommand(1); CLI11_PARSE(app, argc, argv); @@ -135,12 +136,12 @@ int main(int argc, char** argv) { initializeSignalHandler(); - TRESTDAQManager daqManager; + TRESTDAQManager manager; if (!configFilename.empty()) { - int shareMemoryID; + int sharedMemoryID; TRESTDAQManager::sharedMemoryStruct* sharedMemory; - if (!TRESTDAQManager::GetSharedMemory(shareMemoryID, &sharedMemory)) { + if (!TRESTDAQManager::GetSharedMemory(sharedMemoryID, &sharedMemory)) { cerr << "Error accessing shared memory" << endl; return 1; } @@ -152,17 +153,26 @@ int main(int argc, char** argv) { sprintf(sharedMemory->configFilename, "%s", configFilename.c_str()); } TRESTDAQManager::DetachSharedMemory(&sharedMemory); + + // Initialize + + /* + if (!manager.Initialize()) { + cout << "Error initializing DAQ manager" << endl; + return 1; + } + */ if (startupElectronics) { cout << "Attempting electronics startup" << endl; - daqManager.startUp(); - return 1; - } else { - daqManager.dataTaking(); + manager.startUp(); } + this_thread::sleep_for(chrono::seconds(1)); + + manager.dataTaking(); + } else { cout << "Starting infinite loop" << endl; - return 1; - daqManager.run(); + manager.run(); } } } From 19fc6242c14cd7af83f5dc32056a7d106841c9ad Mon Sep 17 00:00:00 2001 From: juanan Date: Fri, 28 Oct 2022 10:36:23 +0200 Subject: [PATCH 13/13] Fixing compilation while using framework cmake --- CMakeLists.txt | 5 ++++- daq/CMakeLists.txt | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2418c22..b0f683f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,8 +40,11 @@ message(STATUS "Package ${PROJECT_NAME} will be installed in ${CMAKE_INSTALL_PRE #-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- #Set include and lib +set(INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) -set(INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/include ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) +if (NOT ${CMAKE_PROJECT_NAME} STREQUAL ${PROJECT_NAME}) + set(INCLUDE_DIRS ${INCLUDE_DIRS} ${rest_include_dirs}) +endif () set(LINK_LIBRARIES ${ROOT_LIBRARIES} RestRaw) string(STRIP "${LINK_LIBRARIES}" LINK_LIBRARIES) diff --git a/daq/CMakeLists.txt b/daq/CMakeLists.txt index 51698db..9374783 100644 --- a/daq/CMakeLists.txt +++ b/daq/CMakeLists.txt @@ -1,7 +1,7 @@ add_library(RESTDAQ SHARED TRESTDAQ.cxx TRESTDAQSocket.cxx DCCPacket.cxx TRESTDAQDCC.cxx FEMINOSPacket.cxx TRESTDAQFEMINOS.cxx TRESTDAQDummy.cxx TRESTDAQManager.cxx) -target_include_directories(RESTDAQ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${ROOT_INCLUDE_DIRS} ${REST_INCLUDE_DIRS}) +target_include_directories(RESTDAQ PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${INCLUDE_DIRS}) target_link_libraries(RESTDAQ PUBLIC ${LINK_LIBRARIES} RestFramework RestRaw)